今天网上碰到了题测试题: 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`;
}
执行的结果是: good and gbc
原因是
字符串是不可修改的,而char[]这个数组的内容是可以修改的。
我运行了下,确实是这样的结果,但是我用另外个类似的类:
public class a
{
static String m=new String("ada");
public static void main(String args[])
{
m="eeeee";
System.out.println(m);
}}运行结果却是:eeeee
为什么会这样呢?不是说字符串不可修改吗?怎么这里又可以修改了?请高人回答!
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`;
}
执行的结果是: good and gbc
原因是
字符串是不可修改的,而char[]这个数组的内容是可以修改的。
我运行了下,确实是这样的结果,但是我用另外个类似的类:
public class a
{
static String m=new String("ada");
public static void main(String args[])
{
m="eeeee";
System.out.println(m);
}}运行结果却是:eeeee
为什么会这样呢?不是说字符串不可修改吗?怎么这里又可以修改了?请高人回答!
m 是引用类型,本来指向"ada",
执行m="eeeee"; 之后m指向的内容变成了"eeeee",但是本来的"ada"还是存在于内存中
外部声明的str
public class Example{
String str=new String("good");
char[]ch={`a`,`b`,`c`};
public static void main(String args[]){
Example ex=new Example();
ex.str=ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
Sytem.out.print(ex.ch); }
public String change(String str,char ch[])
{
str="test ok";
ch[0]=`g`;
return str;
} 结果应该是test ok and gbc
String str = "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[]) {
this.str = "test ok";
ch[0] = 'g';
}
}