I've seen several similar questions, but their answers don't really answer my question.
Where does an old string go when we edit string and a new one is created.
String s1 = "Hello"
s1 += "World"
We had a string Hello but then a new string is created and it is HelloWorld.
Is string Hello still in string pool(i guess no, as we lost reference to it). Is garbage collector going to destroy it?
And what if we create a new string and use intern method. Is this string going to be taken from pool?
String s1 = "Hello";
s1 += "World";
String s2 = "Hello";
In this topic, Stephen C said that
The strings will be garbage collected if they ever become unreachable
But I did such thing:
String s1 = "Hello";
System.out.println(System.identityHashCode(s1));
s1 += "World";
System.gc();
String s2 = "Hello";
System.out.println(System.identityHashCode(s2));
and it printed the same identity hashcode, though I lost reference to the "Hello" string and a new one should have printed another identity hash code.
He also said that
This means that the String is reachable for as long as the method could be executed.
But I did an experiment similar to the above one where the method created a string, then in another method, I created the same string(before used System.gc) and it printed out the same identity hash code.
Why doesn't GC destroy the string in my 2 cases if I lose reference to them?