public class aclass { public static void main (String args[]){ StringBuffer s1 = new StringBuffer("s1"); StringBuffer s2 = new StringBuffer("s2"); method(s1, s2); System.out.println("s1 is "+s1+" ********** s2 is "+s2); } public static void method(StringBuffer b1, StringBuffer b2){ b2.append(" "); b1 = b2; } } why output is "s1 is s1 ************ s2 is s2 " ? thanx.
This is because the arguments of Java method calls are passed by value. Here, the value of s1 ie. the reference to the object of new StringBuffer("s1") not the object, is passed to the method. In the method b1, the reference, is changed not s1. That is, s1 remains the same.
s2, the reference of new StringBuffer("s2"), remains the same. That is, s2 is still a reference to new StringBuffer("s2"). But the object was changed by b2.append(" ");.
Thanx, Peter. In my book, every argument is a copy of something else, so, S2 shouldn't be modified with B2... Im still a little confused about that, can u explain it in detail?
when u pass the refrences to 2 StringBuffers , a copy of each reference is passed . So now there are two refrences to each stringBuffer s1 and b1 for first and s2 and b2 for the second Inside method() b2 is used to append a charachter to second StringBuffer and then b1 is assigned the value of reference b2
so now s1 is a refrence to first stringBuffer and s2, b2 and b1 all three of them refer to second StringBuffer. but remember that b1 and b2 are not visible outside method()