2

I apologise if this question is realy silly but I was wondering if anyone could tell me why this happens:

String helloString = "hello";
String referenceOfHello = helloString;

helloString = "bye";

System.out.println(referenceOfHello);

and the output is hello. I was expecting bye to be output but that didn't happen. I know this is a very basic question but I always thought that referenceOfHello stored the memory location of helloString, instead of its value.

Thanks.

Vancert Staff
  • 195
  • 1
  • 2
  • 12

3 Answers3

4

code with explanation in comment.

String helloString = "hello"; //creates variable in heap with mem address 1001
String referenceOfHello = helloString; //now referenceOfHello and helloString are poimnting  same object

helloString = "bye"; //now, helloString  pointing diff object say 1002, but still, referenceOfHello  will point to 1001 object
niiraj874u
  • 2,180
  • 1
  • 10
  • 19
0
String helloString = "hello";
String referenceOfHello = helloString;

Both references helloString referenceOfHello and are pointing to "hello" object.

helloString = "bye";

helloString reference is now pointing to "bye" object but referenceOfHello reference is still pointing to old "hello" object.

Aniket Thakur
  • 58,991
  • 35
  • 252
  • 267
0

So the strings in Java are immutable, therefore when you write

String helloString = "hello";

You point the reference helloString to the place where "hello" is written in the memory. When you write the next row:

String referenceOfHello = helloString;

referenceOfHello gets pointed that way too. However, when you change the value of the helloString what is happening actually is that another place in the memory gets allocated, the new string gets written in it and the reference gets pointed to it.

However the other reference is already linked to the old string and it does not get pointed to the new one automatically. Thus the printed message is the old one.

Nikola Geneshki
  • 639
  • 7
  • 22