Java String objects equality and reference

Morez :

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.)

Mureinik :

Strings in Java are immutable. You aren't "changing the value of y", you're creating a new string and assigning it to y. Since you haven't assigned anything else to x, it will still reference the previous string you had there.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=396389&siteId=1