Java中只有String类型和基本类型传递副本,副本的改变不会影响原来的值。看下面的代码:
package algorithms.com.guan.javajicu;
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.print(ex.ch);
}
public void change(String str, char ch[]){
str= "test ok";
ch[0]= 'g';
}
}
/*
输出 : goodandgbc
*/
Java中只要值传递,只不过值属于地址还是方法区中的基本类型。
字符数组传递的是引用,因此会被修改。
而字符串作为特殊的引用类型,它的传递属于跟基本类型一样的新建一个副本,因此原来的字符串不变。