Search code examples
stringbuffer

can someone explain this behavior of StringBuffer?


public class StrBuffer {

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();  //5
        sb.append("hello"); //6
        foo(sb); //7
        System.out.println(sb); //8
    }

    private static void foo(StringBuffer sb) {
        // TODO Auto-generated method stub
        sb.append("wow");    //1
        sb = new StringBuffer();  //2
        sb.append("foo"); //3
        System.out.println(sb); //4     
    }
}

in the above when i print in line8. output is "hellowow" .... can some one explain this please?


Solution

  • At first, you pass a reference to main's sb to foo. In foo, you append "wow" to the referenced object.

    Then, in foo, you create a new StringBuffer object, and change the local sb to point to it.

    It might be clearer if I rename the reference:

    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();  //5
        sb.append("hello"); //6
        foo(sb); //7
        System.out.println(sb); //8
    }
    
    private static void foo(StringBuffer ref) {
        ref.append("wow");    //1
        ref = new StringBuffer();  //2
        ref.append("foo"); //3
        System.out.println(ref); //4     
    }
    

    'ref', as passed in to foo, is a just a reference to main's sb. You can operate on ref (ie., sb) in foo until you changed ref to refer to a different object.