Search code examples
javastringbuffer

Why this code is not giving the output as expected


I was expecting the output as AB , ABCD but the output is ABCD , B. How's that possible?


    public class Test {
           public static void main(String[] args) {
                 StringBuffer a = new StringBuffer("A");
                 StringBuffer b = new StringBuffer("B");
                 operate(a, b);
                 System.out.println(a + " " + " , " + " " + b);

           }

           static void operate(StringBuffer x, StringBuffer y) {
                 x.append(y);
                 y = x.append("C");
                 y.append("D");
           }
    }


Solution

  • So initially, you have this.

    a -> [A...]         b -> [B...]
    

    then when you call operate, you get two new variables referencing the same two StringBuffer objects.

    a                   b 
       ->  [A...]          ->  [B...]
    x                   y
    

    Then you append the contents of one StringBuffer to the other.

    a                     b 
       ->  [AB...]           ->  [B...]
    x                     y
    

    Then you append another letter to the first StringBuffer, and re-point the variable y so that it now references the same StringBuffer as a and x.

    a                      
    x  ->  [ABC...]        b   ->  [B...]
    y                     
    

    And you append one more letter, now referencing the first StringBuffer as y.

    a                      
    x  ->  [ABCD...]        b   ->  [B...]
    y                     
    

    Then you exit from operate and print out the contents of both StringBuffer objects.