Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String assignments and output

Tags:

java

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.

like image 465
Rouki Avatar asked Feb 10 '26 13:02

Rouki


2 Answers

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

like image 173
Moritz Petersen Avatar answered Feb 15 '26 14:02

Moritz Petersen


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.

like image 27
Sergey Kalinichenko Avatar answered Feb 15 '26 14:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!