字符串分配和输出

Rou*_*uki 2 java

给出以下代码:

String str1 = new String("Hello");
String str2 = str1;
String str3 = new String(str1);
String str4 = str3;
str4 += " World ";
if (str3==str4)
     System.out.println(“one”);
if (str3.equals(str4))
     System.out.println(“two”);
if (str1==str2)
     System.out.println(“three”); 
if (str3.equals(str2))
     System.out.println(“four”);
Run Code Online (Sandbox Code Playgroud)

输出为:三和四

我不明白..我们刚刚做了str3 == str4.怎么他们不能引用同一个对象..?str3 == str4似乎是假的,我不明白为什么.另外,str3.equals(str4)也返回false,但我想这与我得到的第一件事情有关.

很想得到解释.

Mor*_*sen 7

因为a String是不可变的,所以+=运算符创建一个新实例并将其分配给它str4.因此str4不相等str3.