2

I know that Strings are stored on the heap and the reference to them is stored on the stack. So in the code below one would point to "John" on the heap from the stack and likewise two would point to "Smith" on the heap from the stack.

So what happens when i do one = two? Does one now point to where two points to because two contains a reference to a point on the heap or does it change the "John" on the heap to "Smith"?

String one;
one = "John";
String two = "Smith"
one = two;
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
user3562135
  • 159
  • 2
  • 9
  • Why would it keep 2 versions of the same exact string if it doesn't have to? – takendarkk Apr 30 '14 at 21:39
  • 1
    Your question has nothing to do with what is on the stack and what is on the heap. You could make it clearer by removing references to both. – Blorgbeard Apr 30 '14 at 21:39

2 Answers2

5

In your example, one now points to the same place as two. The original string on the heap "John" becomes garbage and is subject to garbage collection.

It's not possible to see in this example because String is immutable, but if these were mutable data structures such as an ArrayList, then modifying the object through one would make the same change visible through two, because they point to the same object.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

Now one will point to the two .
Since all string are immutable then when they are created then they are stored in heap and referenced by variable but when you make or assign new variable to same string then it will not explicitly create new string but just reference to same string which is in heap
enter image description here

from above picture you can easily understand the concept of immutability.
for reference Where does java reference variable stored?

Community
  • 1
  • 1
Devavrata
  • 1,785
  • 17
  • 30