5

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?

10
  • 3
    Run your test 1000 times. The GC runs when the GC runs. You can't get deterministic results. Commented Aug 4, 2018 at 15:19
  • As far as I know, strings in the string pool do not get garbage collected. Commented Aug 4, 2018 at 15:22
  • 2
    Please don't reask the same question. If you don't think the duplicate(s) applies, edit your question to explain why, then wait for the reopen votes to come in. Commented Aug 4, 2018 at 15:23
  • @SotiriosDelimanolis I apologize. I created a new question, as I edit the previous one with the additional explanation and it wasn't reopened. I guess I should've waited more. Commented Aug 4, 2018 at 15:40
  • 2
    The cited answer also says: “In practice, the String objects that correspond to string literals typically do not become candidates for garbage collection. This is because there is an implicit reference to the String object in the code of every method that uses the literal.” Commented Mar 26, 2021 at 17:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.