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 ");
for(int i=0;i<ex.ch.length;i++){
System.out.print(ex.ch[i]);
}
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
A good and abc B good and gbc
C test ok and abc D test ok and gbc
java 中只有值传递,在方法参数中传递的都是副本。
如果传递的是原始类型(byte, short, int, long...),传递过来的就是这个参数的副本,也即参数的值。
如果传递的是引用类型(class, interface, array...),传递的就是引用参数的副本,(引用类型可理解为指向一个特定数据存储区的变量)。
void change(String str,char ch[])
里传递的都是引用副本,如果在方法内修改了引用指向,比如str="test ok";
那么原来的引用ex.str ex.ch
还是不会变的, 但是改变引用指向存储区的数据ch[0]='g';
,所有引用获取的数据都会改变(指向的都是同一个区域)。