StringBuffer behaviour

160 Views Asked by At
public class Test {
    public static void main (String [] args) {
        TestMathRandom x = new Test();
         StringBuffer a = new StringBuffer ("A");
         StringBuffer b = new StringBuffer ("B");
         x.operate (a,b);
         System.out.println(a + "," +b);
    }

    void operate (StringBuffer x, StringBuffer y) {
         x.append(y);
         y = x;

    }
}

Ans is AB,B Please tell me why value of b is unchanged.

3

There are 3 best solutions below

0
Alessio On

You are passing values of the variables x and y, not a reference to them. So the changed made inside the operate function are useless, follow the link provided as a comment to your post to understand better ;)

0
Vimal Bera On

Passing StringBuffer in parameter of method operate is passbyvalue. In this type, the value of variable is just copied into the temp variable defined in method's parameter. Means in your example value of both a and b are just copied in x and y. Here value of a got changed but b didn't.
Its obvious. Here value of b didnt change because y is the mirror copy of b. But append function works with actual value. It takes reference of x and append the y with it and ultimately it shows change at a.

0
Evgeniy Dorofeev On

This is because in Java arguments are passed by value. So y = x just changes local var y value in operate method.