Please pardon the beginner question.I met this code fragment on the internet:
public class Person {
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)
{
y.append(x);
y=x;
}
}
I figured out the running output should be A,A, however, the correct output should be A,BA, could expert help me understand why the value of b is still AB? Why “y.append(x)” will affect the value of b, but not “y=x”? That is where I am getting confused.
Thanks in advance.
The short answer is that Java arguments are passed by value, so the final assignment in
operatedoesn’t have any effect.The detailed sequence of events is as follows:
aandbare initialized to two StringBuffer objects. Lets write this asThe (trivial) argument expressions for the
operatorcall arguments are evaluated giving S1{“A”} and S2{“B”}.The call starts, and the two references are assigned to the local variables
xandy. So the state is now:The
y.append(x)call modifies the S2 object:The
y = x;assignment is performed:The
operatemethod returns, causingxandyto go out of scope.The key thing to note is that in step 5 we DID NOT change the contents of the S2 object. Instead, we just changed
yto refer to the other object.