I'm trying to see how string object works in Java.
String value1 = "Good";
String value2 = "Good";
System.out.println(Integer.toHexString(value1.hashCode()));
System.out.println(Integer.toHexString(value2.hashCode()));
System.out.println(value1 == value2);
And it shows the same address
21f4dd
21f4dd
true
I know that these 2 variables point to the same object which is stored in heap. But I'm stuck when using concatenation.
String value3 = "Bad";
System.out.println(Integer.toHexString(value3.hashCode()));
value3 += " enough";
System.out.println(Integer.toHexString(value3.hashCode()));
String value4 = "Bad enough";
System.out.println(Integer.toHexString(value4.hashCode()));
System.out.println(value3 == value4);
It shows
103e5
c35f20b
c35f20b
false
After concatenation, there is a new string object whose value is "Bad enough". I assign this object to 2 variables, value3 and value4 also print their address.
My question is that the address of value3 and value4 are the same, so it means they point to the same object but why Java return false when comparing these 2 variables?