Java字符串是不可变的吗? [英] Is Java String immutable?
问题描述
我不理解此代码,为什么我的字符串c
不能在main
方法中更改而在changeString
中更改.你能解释一下吗?
I don't understand this code, why my string c
don't changing in main
method but changing in changeString
. Can you explain me?
class MainClass {
public static void main(String[] args) {
String c = "lalala";
changeString(c);
System.out.println("str in main = "+c);
}
public static void changeString(String str) {
str = str + "CHANGE!!!";
System.out.println("str in changeString = "+str);
}
}
结果:
str in changeString = lalalaCHANGE!!!
str in main = lalala
推荐答案
是的,java字符串是不可变的.
Yes, the java string is immutable.
在changeString
中,您传递了对字符串lalala
的引用,然后将 reference 更改为指向lalalaCHANGE!!!
的引用.原始字符串对象未更改,main
中的引用仍引用该原始对象.
In changeString
, you are passing in a reference to the string lalala
and then you are changing the reference to one that points to lalalaCHANGE!!!
. The original string object is not changed, and the reference in main
still refers to that original object.
如果要使用StringBuilder而不是字符串,并将CHANGE!!!
附加到该StringBuilder,那么您将在main上查看它时看到更改:
If you were to use a StringBuilder instead of a string, and append CHANGE!!!
to that StringBuilder, then you would see the change reflected in viewing it at main:
class MainClass {
public static void main(String[] args) {
StringBuilder c = new StringBuilder("lalala");
changeString(c);
System.out.println("str in main = "+c.toString());
}
public static void changeString(StringBuilder str) {
str.append("CHANGE!!!");
System.out.println("str in changeString = "+str.toString);
}
}
在此更改的版本中,您将获得:
In this changed version you would get:
str in changeString = lalalaCHANGE!!!
str in main = lalalaCHANGE!!!
这篇关于Java字符串是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!