Given the following code:
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”);
The output is : Three and Four
I don't get it.. we just did str3 == str4 . how can they NOT refer to the same object..? str3 == str4 seem to be false and I dont get why. In addition, the str3.equals(str4) also return false but I guess that has something to do with the first thing I dont get.
Would love to get an explanation.
Because a String is immutable, the += operator creates a new instance and assignes it to str4. Therefore str4 is not equal str3.
Here is what happens: str3 and str4 start off referencing the same object. However, since Java String is immutable and thus cannot be modified in-place, this line
str4 += " World ";
results in assigning str4 a reference to a brand-new object. That is why the subsequent comparison str3==str4 fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With