In line 1, when we are passing (String , StringBuffer) as (s1, s2), we are only passing a copy of s1 & s2 to the method in line 2. so any changes done to s1 & s2 inside the method, puto(String s1, StringBuffer s2) should not really change the values of s1 & s2. so in line 3, s1 is printed as "W" which is expected.
But in line 4, s2 is printed as "WO". how come the changes done to s2 in the method, puto(String s1, StringBuffer s2) is reflected, when s2 is printed in main() method.? i expected s2 should be printed "W" too!
can anyone explain why?
Because Strings are immutable and StringBuffers are mutable. You passed a copy of the reference to the String, and to the StringBuffer. When you "modified" the String, it actually created a new String object and pointed to that. However, since StringBuffers are mutable, when you made a change it was made to the same object that is in the main method, since both variables hold a reference to teh same object.
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
Notice the extra untrimmed space in front of W in case of s1.
And that is exactly what it should be. There are two concepts at play here:
1. When we pass a reference we do pass a copy, but it is copy of the bits, that refer to the SAME object. So there are two references (the original and the copied) but they are both refering to the same object. There is just one object.
After the method is over, any changes that you make to the object itself will be continue to be reflected after the method is over. Any change that you make to the reference (e.g. making it point to a different object) will not be reflected.
2. String object is immutable. When you pass it to a method, you are still passing a copy of reference to the same object (just like in 1). But when you make any changes inside the method, the original String cannot be changed and so a new one is created. Original object is untouched. And ofcourse, that original object is exactly what you have a reference to in the main method.
Please correct me someone if I am wrong!
"A problem well stated is a problem half solved.” - Charles F. Kettering
SCJP 6, OCPJWCD
Joined: Mar 09, 2006
Thanks for the clarification!
the output was actually,
but the spaces before W did not get copied here
subject: Behaviour of String and StringBuffer class.