public static void main(String[] args){
String s1="hello";
String s2="world";
changeStr(s1,s2);
System.out.println(s1+"--"+ s2);
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
changeSb(sb1,sb2);
System.out.println(sb1.toString()+"--"+sb2.toString());
}
public static void changeStr(String x,String y){
x = y;
y = x+y;
}
public static void changeSb(StringBuffer x,StringBuffer y){
x = y;
y.append("****add a tail");
}
对以上两句话的执行结果,第一个是没有问题的,都知道是:hello--world
然而第二句话,以为执行结果是:world--world****add a tail ,但其实结果是:hello--world****add a tail
从堆栈的角度来理解
StringBuffer传递到changeSb方法里的是引用,这里特意写了形参为x,y就是为了避免混淆:
在changeSb方法里,两个地址的名称是x,y,假如x对应地址0x1111,y对应地址0x2222,当change方法执行到最后,
x中保存的地址是0x2222,y中保存的地址是0x2222,此时
0x1111对应的内容---------"hello"
0x2222对应的内容---------"world****add a tail";
而在main方法里,两个地址的名称是sb1,sb2,
sb1中保存的地址是0x1111,sb2中保存的地址是0x2222,
所以打印出的结果应该是 hello--world****add a tail
(参考:https://blog.youkuaiyun.com/qq_38225558/article/details/82054486)