首先需要确定的是s1和s2都是引用类型变量,即栈内存中的s1和s2变量指向堆内存中的对象
s1 = a1;
s2 = a
package Junit;
/**
* 结果:a12--a12 a122a122--a122a122 这个结果是怎么来的啊
*
* @author Administrator
*
*/
public class HelloWorld {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("a");
StringBuffer s2 = new StringBuffer("b");
s1.append("1"); //s1 = a1
s2 = s1; //s2 = a1
s2.append("2"); //s2 = a12 s1 = a12 因为s1和s2指向堆中同一个对象
System.out.println(s1 + "--" + s2); //输出结果为:a12--a12
HelloWorld t = new HelloWorld(); //s2 = a12 s1 = a12 指向同一个对象
t.change(s1, s2); //过程在下面
System.out.print(s1 + "--" + s2); // 结果显示: a122a122--a122a122
}
public void change(StringBuffer s1, StringBuffer s2) {
// s1=new StringBuffer("c");
s1.append("2"); //s1 = a122
s2 = s1; //s2 = a122
s2.append(s1); //s2 = a122a122 s1 = s2 = a122a122
}
} |
|