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.
Joined: Jul 25, 2001
Peter: Why is that not the case with s2 and b2?
Joined: Oct 03, 2001
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(" ");.
Joined: Sep 10, 2001
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?
Joined: Sep 05, 2001
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()