帮忙看一道java的题目..

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 c[]){str="test ok"; ch[0]='g'; } }
A、 good and abc B、 good and gbc C、test ok and abc D、 test ok and gbc

为什么选A?
经过验证,是选B的 答案错了

选项是B不是A
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 c[]){
str="test ok";
ch[0]='g';
}
}
因为str的类型是String,String的值是不能修改的,所谓的修改只会新创建新的String,而ex.str依然指向原来的String地址,所以它的值没有改变,依旧是“good”。 如果你想让其修改可以试试这么写,将String换成StringBuilder或者StringBuffer,当然你也可以修改change方法:
public class Example {
StringBuilder str=new StringBuilder("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(StringBuilder str,char c[]){
str.replace(0, str.length(), "test ok");
ch[0]='g';
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-12-26
选 B
因为str是String类型,String的值是不变对象的,所谓的不变对象就是每次创建新的String,就是在堆中产生一个新的对象。因此ex.str属性依然指向原来的String地址,其它的值还是指向原值,没有改变。 而ch都指向同一个,修改的是ch指向的地址的内容,所以改变。
第2个回答  2012-12-25
1.str的类型是String,String的值是不能修改的,所谓的修改只会新创建新的String,而ex.str依然指向原来的String地址,所以它的值没有改变。
2.数组传递的是引用,即指向地址空间的变量,所以用这个变量来修改值时也就修改了内存地址空间里的值,因为这个地址里的数据是所有指向该地址的变量所共有的,所以在调用函数时,数组的值会发生改变
第3个回答  2012-12-25
我理解你的问题是为什么change方法没能起作用对吧
其实,是因为当str和char作为参数时,它们只是把自己的引用地址传给了2个参数,所以change方法内部这两个变量其实不是这两个属性,因此改变它们的值自然也影响不到这个两个成员变量了追问

ch[0]='g'; 这不是改变对象的值了吗?

第4个回答  2012-12-25
好吧, 用编译器, 答案是 good and gbc
注意change方法参数名是c[] 方法体中是ch[0]但是这影响不大
相似回答