Since it passed the object myOtherSample by reference and made it point to the object s2, shouldn't the output become: 4 4.95 4 0 ?
-
1*and made it point to the object s2* Can't do that part that's why. `s.j = p;` would do it though. `s = s2;` updates the value of `s` in `f`, but it can't update the original caller's reference. – Elliott Frisch Dec 10 '18 at 05:02
-
Instead of creating s2, assign the values to s itself and try – venkat Dec 10 '18 at 05:20
2 Answers
Since it passed the object myOtherSample by reference and made it point to the object s2, shouldn't the output become: 4 4.95 4 0 ?
Java is always passing by value: Is Java "pass-by-reference" or "pass-by-value"?
You created a Sample ojbect, and make myOtherSample
pointing to it,outside the f
function. By calling f(myOtherSample,i)
, the myOtherSample
value(a pointer of which the value is an address) is passed to the s
which is defined inside the f
function scope. So now pointer s
is pointing to the Sample object, here you can change the j
value of that Sample object by using the pointer s
.
But after that the pointer s
is reassigned to a new Sample object which is created inside the f
function(s=s2
), the Sample object that myOtherSample
is pointing to will not be changed if you make any change to the object that pointer s
is pointing to now.
That is what happened in your code. You should know more about the Java implicit pointer
.

- 4,491
- 1
- 27
- 39
It actually is not being passed by reference in the way that you are thinking. It's best to understand that reference variables (mySample, myOtherSample, s, and s2) are actually just holding the location of where an object is in memory. As a result, s is a completely separate variable from myOtherSample. It just points to the same object in memory since myOtherSample is the parameter for f. When you set s = to s2, s no longer is pointing to the same object as myOtherSample. myOtherSample is not affected, however, because it is a completely separate variable. This concept can be tricky at times, perhaps look into drawing box-arrow diagrams as that can help.

- 56
- 5