Forums Register Login

doubt with StringBuffer

+Pie Number of slices to send: Send
public class Test6{
public static void method(StringBuffer x){
x.append(" Added");
x = new StringBuffer("Hai");
}
public static void main(String a[]){
StringBuffer sb = new StringBuffer("String Buffer");
method(sb);
System.out.println(sb);
}
}

The output is:
"String Buffer Added"

Can someone explain why?
+Pie Number of slices to send: Send
 

Originally posted by shyam kumarK:
public class Test6{
public static void method(StringBuffer x){
x.append(" Added");
x = new StringBuffer("Hai");
}
public static void main(String a[]){
StringBuffer sb = new StringBuffer("String Buffer");
method(sb);
System.out.println(sb);
}
}

The output is:
"String Buffer Added"

Can someone explain why?




StringBuffer and StringBuilder are mutable (can be modified internally). You pass a copy of the reference variable to the method,
so the method will have a new copy of the reference variable that points to the same object the calling method reference variable is pointing to. So whatever modification the called method will do on the StringBuffer the effect will be on the calling method StringBuffer too; In other words there is only one object on the heap and two reference variables pointing to same object.

And yeah, if the called method tries to change the reference, the effect will be local to the method only. There wont be any effect on the calling method StringBuffer.

Thanks,
[ May 06, 2007: Message edited by: Chandra Bhatt ]
+Pie Number of slices to send: Send
i knew immutability of StringBuffers but confused about what happens after reference changes as in:
x = new StringBuffer("Hai");
now i got it Before the reference is changed whatever changes are made will reflect in the original object

thanks bhat
+Pie Number of slices to send: Send
 


i knew immutability of StringBuffers but confused



StringBuffer is mutable as Chandra pointed out, not immutable.

Cheers,
+Pie Number of slices to send: Send
 


i knew immutability of StringBuffers but confused about what happens after reference changes as in:




StringBuffer/StringBuiilder are mutable (you can mutate them)



Thanks,
+Pie Number of slices to send: Send
oh sorry i meant mutability
+Pie Number of slices to send: Send
No more posts regarding this particular mistake of putting
immutability in place of mutability
this has been pointed out already
and POOF! You're gone! But look, this tiny ad is still here:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 739 times.
Similar Threads
StringBuffer Question
confusion about stringbuffer
String Buffer
StringBuffer Doubt
Please explain me ? StringBuffer
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:37:33.