【发布时间】:2019-01-08 02:38:16
【问题描述】:
我正在学习字符串概念,所以写了一个代码,期望不同的输出,但得到了一些非常意想不到的东西。
class stringmute
{
public static void main(String[] args)
{
String s1="Hello "; //string one.
System.out.println("Str1:"+s1);
String s2= s1+"world"; //New String.
System.out.println("Str2="+s2);
s1=s1+"World!!"; //This should produce only Hello right?
System.out.println("Str1 modified:"+s1);
}
}
当我执行上面的代码时,我得到的输出是:
Str1:Hello
Str2=Hello world
Str1 modified:Hello World!!
如果我做错了什么,请告诉我。 由于字符串是不可变的,这意味着我们应该将“Str1 Modified”的输出作为“HELLO”而不是“HELLO WORLD!!”。
【问题讨论】:
-
这应该是理解不变性的好读物。 stackoverflow.com/questions/8798403/…
-
字符串对象是不可变的。对字符串的引用不是(必要的)。
标签: java string immutability