经典面试题解答

public class Example{
	String str = new String("good");
	char[] ch = {'a', 'b', 'c'};
	public static void main(String args[]){
		Example ex = new Example();
		ex.change(ex.str, ex.ch);
		System.out.print(ex.str + " and ");
		System.out.println(ex.ch);
	}
	
	
	public void change(String str, char ch[]){
		str = "test ok";
		ch[0] = 'g';
	}
} 

输出为:good and gbc

在change(String, char[])方法内,ex.str单向传递给str,str改变了,但是ex.str不会随之改变,

str是按值传递,所以在函数中对它的操作只生效于它的副本,与原字符串无关;

ch是按地址传递,在函数中根据地址,可以直接对字符串进行操作。

原文地址:https://www.cnblogs.com/leihupqrst/p/3723132.html