-
Problem with code
I have this code:
Code:
public class Test {
public static void main (String[] args) {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("[B]DD[/B]");
chng(a,b);
System.out.println(a+","+b);
}
static void chng(StringBuffer x, StringBuffer y) {
y.append(x);
System.out.println("y 1: "+y);
y = x;
System.out.println("y 2: "+y);
System.out.println("x 2: "+x);
}
}
The results are;
y 1: BA
y 2: A
x 2: A
A,BA
I want to know why the last line of the result no equal to A,A?
-
Hi,
Because u made a side effect on the StringBuffer b by the append().
-
StringBuffer y is a copy of the reference to StringBuffer b. As long as the reference y continues to refer/point to this same StringBuffer, modifications in y will affect b. When you point y to another StringBuffer then modifications to y will no longer affect b.
See How Arguments Are Passed to Java Methods for discussion.
-
thanks
It was driving me crazy