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.

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, this answer is great. I now understand. Thanks very much for the answer.
Vancert, please accept answer if you finds it helpful. so that other users can take benefit from knowing that the answer works
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.