0

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

Morez
  • 2,085
  • 2
  • 10
  • 33
  • look this https://stackoverflow.com/questions/279507/what-is-meant-by-immutable – User8500049 Apr 03 '20 at 12:58
  • 2
    Having equal hashcodes do *not* mean the objects are the same! Hashcode is an int so here are only 4 billion possible hashcodes, but there are many more possible strings, so there must be collisions. – David Zimmerman Apr 03 '20 at 13:15

2 Answers2

4

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

I think this question ultimately stems from your misunderstanding that x and y are objects. x and y are not objects.

x and y are variables and since String is a reference type, x and y store references to objects. The = assignment operator changes what reference these variables store.

In these two lines:

String x = "a";
String y = "a";

x and y store references that refers to the same object.

But when you do y = y + "b", the y + "b" creates a new object. Then the = make y store a reference to that new object, so y no longer points to the same object as x.

Sweeper
  • 213,210
  • 22
  • 193
  • 313