1) 指出下列程序运行的结果
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 ");
Sytem.out.print(ex.ch);
}
public void change(String str,char ch[]){
str="test ok";
ch[0]='g';
}
}
char[0]复制了引用之后还指向原来的内存,并且因为可以修改值,所以
因此str=“abc”;str="qwe";相当于又new了一块新内存,str引用指向新的内存。在方法中传入str相当于复制了一个引用指向原来的内存,而新的引用指向其他内存后,原来的引用和指向的内存不变;
2) 指出下列程序运行的结果
public class Example{
StringBuffer str=new StringBuffer("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 ");
Sytem.out.print(ex.ch);
}
public void change(String str,char ch[]){
str=new StringBuffer("qwe");
ch[0]='g';
}
}
同理因为str new了一块新的内存,并不会影响原来的值。
但如果把str=new StringBuffer(''qwe'');变成str.append("qwe")这样就会把原来的good变成goodqwe
这个题再看到不要错了!!!