I have some questions revolving around the garbage collection of string objects and literals and the string pool.
Setup
Looking at a code snippet, such as:
// (I am using this constructor on purpose)
String text = new String("hello");
we create two string objects:
"hello"creates one and puts it into the string poolnew String(...)creates another, stored on the heap
Garbage collection
Now, if text falls out of scope and nobody references them anymore, it can be garbage collected, right?
But what about the literal in the pool? If it is not referenced by anyone anymore, can it be garbage collected as well? If not, why?
When we create a String via the
newoperator, the Java compiler will create a new object and store it in the heap space reserved for the JVM.To be more specific, it will NOT be in the String Pool, which is a specialized part of the (heap) memory.
As soon as there is no more reference to the object it is eligible for GC.
In contrast, the following would be stored in the string pool:
When we call a similar line again:
The same object will be used from the String Pool, and it will never be eligible for GC.
As to why: