2

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.

Rouki
  • 2,239
  • 1
  • 24
  • 41
  • this is a duplicate, please browse the site for similar questions . :) – PermGenError May 14 '13 at 14:14
  • 3
    duplicate..? how come? I did look for similar questions. – Rouki May 14 '13 at 14:15
  • this one..? http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java? That doesnt answer my question. – Rouki May 14 '13 at 14:15
  • 3
    `str4 += " World ";` changes the value of `str4` - it's as simple as that. After that statement, `str4` refers to a string with contents `Hello World ` but `str3` still refers to a string with contents `Hello`. So they're not only distinct string objects, but objects with different contents. – Jon Skeet May 14 '13 at 14:17
  • 5
    This is not a duplicate. The OP clearly knows how to compare strings, but the confusion comes from misunderstanding of how object references work in conjunction with string immutability. – Sergey Kalinichenko May 14 '13 at 14:17
  • 6
    This question is not about comparison but about the `+=` operator. – Moritz Petersen May 14 '13 at 14:18
  • Because a `String` is immutable, the `+=` operator creates a new instance and assignes it to `str4`. Therefore `str4` is not equal `str3`. – Moritz Petersen May 14 '13 at 14:18
  • How would you get as you had appended str4 += " World "; ? – commit May 14 '13 at 14:19

2 Answers2

7

Because a String is immutable, the += operator creates a new instance and assignes it to str4. Therefore str4 is not equal str3.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523