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); } }
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.
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