java如何处理字符串文字 [英] how java handles string literals
问题描述
在java中,我创建了2个具有相同值的字符串文字
in java, i have created 2 string literals having same value
String a = "Hello";
String b = "Hello";
现在两者都应该有相同的参考
now both of them should have same reference
System.out.println(a==n); // returns true
但是当我这样做时
b+=" World";
System.out.println(a==b); // returns false
现在我有2个问题在这里
1.为什么a 'b + ='操作后,b不引用同一个对象?
2.为什么我能更改字符串b而没有任何错误?(因为我读过String类是不可变的)
Now i have 2 questions here
1. why a and b are not referencing to same object after 'b+=' operation?
2. how come i'm able to change string b without any error?(because i have read String class is immutable)
推荐答案
您可以更改 b
的原因是因为您在技术上制作了一个新的String对象并将其分配给现有的引用。
The reason you can change b
is because you're technically making a new String object and assigning it to the existing reference.
b += " World"
与
b = b + " World";
b
技术上指向一个新字符串宾语。首先, a
和 b
指向同一个对象,但是当 b时
被修改它现在是一个不同的对象,所以 a
将不等于Hello World
和 a == b
现在将为false。
b
is technically pointing to a new String object. So to start out, a
and b
are pointing to the same object, but when b
is modified it is now a different object, so a
will not equal "Hello World"
and a==b
will now be false.
有关可变String类的示例,请尝试 StringBuffer
或 StringBuilder
。您可以使用他们的 .append()
方法添加到字符串中,以及其他方法来修改它。
For examples of mutable String classes, try StringBuffer
or StringBuilder
. You can use their .append()
method to add to the string, along with other methods to modify it.
这篇关于java如何处理字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!