. Primitives are always passed by value.
. Object "references" are passed by value. So it looks like the object is passed by reference but actually it's the value of the reference that is passed.
A crude example:
Object o1 = new Object(); //say, the object is stored at memory location 15000. So o1 actually contains 15000.
now, when you call someMethod(o1); the value 15000 is passed.
Inside the method someMethod
someMethod( Object localVar)
......localVar contains 15000 so, whatever method you call or modication you do to this varibale, it is done on the original object. But when you try to change it's value, for eg. make it null, it then contains 000000 (say). But the original variable o1 still contains 15000 so it still points to the same object.
The next question is based on the above concept.
You created two objects in main method:
s1 ------------> [ EMPTY ] STACK 1 OBJECT
s1 actually contains 15000 (say)
s2 ------------> [ EMPTY ] STACK 2 OBJECT
s1 actually contains 25000 (say)
inside the method assign() :
s1 ----> [ EMPTY ] STACK 1 OBJECT <----x1 Local variable<br /> s1 and x1 both contain 15000 (say)<br /> s2 ----> [ EMPTY ] STACK 2 OBJECT <----x2 Local variable<br /> s2 and x2 both contain 25000 (say)<br /> <br /> Step 2;<br /> s1 -----> [ 100 ] STACK 1 OBJECT <----x1 Local variable<br /> Because x1 is refering to the same memory location.<br /> s2 -----> [ EMPTY ] STACK 2 OBJECT <---x2 Local variable<br /> Step 3: After doing x2 = x1<br /> s1 ---> [ 100 ] STACK 1 OBJECT <---- x1 and x2 Local variables<br /> s1 and x1 both contain 15000 (say) and x2 now also contains 15000.<br /> <br /> s2 ------------> [ EMPTY ] STACK 2 OBJECT
But s2 still contains 25000.
Note that it's the local variable x2 that is pointing to the same object as x1, which is s1 stack object. The original s2 (of the main method) is still pointing to the same object which is empty.
So when you come back to the main method, you print s1 (which has now 100) and s2( which is still empty)
Get Certified, Guaranteed!