I have the following code:
public class Test{
public static void main(String []args){
String x = "a";
String y = "a";
System.out.println(System.identityHashCode(x) == System.identityHashCode(y)); //true
System.out.println(x.hashCode() == y.hashCode()); //true
y = y+"b";
System.out.println(x); // "a"
System.out.println(y); // "ab"
System.out.println(System.identityHashCode(x) == System.identityHashCode(y)); //false
System.out.println(x.hashCode() == y.hashCode()); //false
}
}
First I create 2 Strings x and y. Then I check their HashCodes and they are same so it means they are one object and they point to one memory location. But when I change y value, The value of x won't change. If I check their hashcode again, They are different so that means 2 different objects and 2 different memory locations. Why does that happen? Why doesn't x change when y changes? (because we are just changing the content of one memory)
I used hashcode as this question suggests.
Update: My confusion was for 2 reasons:
a) I thought same hashcodes mean same objects (You can have a look at this and this questions for the detailed explanation why I'm wrong.)
b) Strings are immutable and if the value changes, New Strings are created (As explained in the answers below.)