How String object is garbage collected in java?

garbage-collection, java, string

Solution

Whenever you call `new` in JAVA it create an object in heap but in case of String literals, it will go into the String Constant Pool.

Sample code:

String value = new String("ABC");
value = "xyz";

Now in the above sample code "ABC" and "xyz" string literals will go to the String Constant Pool and will not be garbage collected but finally `value` is referring to "xyz" from the String Constant Pool.

So basically there are 3 objects, 2 in the String Constant Pool and 1 in the heap.

at which point previously created String object will be garbage collected?

The object is created by `new` will be garbage collected once its scope/life is finished or there is no reference to access it. It's applicable similarly for all the objects including String as well.

Since the `value` reference will be pointed to the existing object with the value "xyz" within the string constant poll in the next line, so that previously created object using `new` in the heap is eligible for garbage collection but not "ABC" string literal that is still in the string constant pool.

Try to visualize it.

Read more...

Problem

As we know when ever we are creating String object like `String value = new String("ABC");` then new `String` object will be created and when we use value variable again as `value="xyz"` then a new `String` object will be created. So my question is that at which point previously created `String` object will be garbage collected?

Original source

Related problems