第一个例子:基本类型 void foo(int value) { value = 100; } foo(num); // num 没有被改变 第二个例子:没有提供改变自身方法的引用类型 void foo(String text) { text = "windows"; } foo(str); // str 也没有被改变 第三个例子:提供了改变自身方法的引用类型 StringBuilder sb = new StringBuilder("iphone"); void foo(StringBuilder builder) { builder.append("4"); } foo(sb); // sb 被改变了,变成了"iphone4"。 第四个例子:提供了改变自身方法的引用类型,但是不使用,而是使用赋值运算符。 StringBuilder sb = new StringBuilder("iphone"); void foo(StringBuilder builder) { builder = new StringBuilder("ipad"); } foo(sb); // sb 没有被改变,还是 "iphone"。
重点理解为什么,第三个例子和第四个例子结果不同?
下面是第三个例子的图解:
builder.append("4")之后
下面是第四个例子的图解:
builder = new StringBuilder("ipad"); 之后
作者:Intopass
链接:https://www.zhihu.com/question/31203609/answer/50992895
来自知乎
再如一道经典例题
public class foo { public static void main(String sgf[]) { 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) { x.append(y); y=x; } }
输出“AB.B”