new MWC205().m3(s1); System.out.print("Three "+s1); } }
Could anyone please explain me in detail, why the output of "Three" is AB instead of C.
The reason is that when a reference is passed as a parameter to a method, only a copy of the reference is sent. In the first line of m2, s1, the formal parameter, is set to point to a different object. Since this is just a copy of the original reference, it doesn't change the original reference.
First thing to know is java uses pass by value methodology for passing argument to method. S1 is a reference object. When you call [ new MWC205().m1(s1); ] method m1 you are passing reference of s1 by value i.e. A copy of original reference to s1 is passed to method m1 . Now at this point original reference and a copy reference both are pointing to same object , so inside method m1 " S1.append("B") " will change the original object and it will hold value "AB" . On call to method m2 " new MWC205().m2(s1); " a copy of original reference to s1 is passed to m2 . Inside method m2 a new object of same name s1 is created and displayed as output [ note here this new object s1 has nothing to do with original reference of s1 , this is a complete new object ] . At step " new MWC205().m3(s1); " no change is done to reference object s1 , only the value is displayed . Hence the final value which object s1 is holding is " AB " .