Reputation: 561
String s = "hello";
String literals have references in String Literal Pool and are not eligible of garbage collection, ever. So, after above line even if I say:
s=null;
String object "hello" will still be in heap as I understand. Source: https://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html
Does same holds true for strings inside String array? Suppose we have
String[] arr = {"one","two","three"};
arr=null;
Will the 3 string objects still be on heap referenced from pool? or they will be eligible for garbage collection along with array object.
Upvotes: 0
Views: 115
Reputation: 719436
String literals have references in String Literal Pool and are not eligible of garbage collection, ever.
Actually, that is not strictly correct ... see below.
Will the 3 string objects still be on heap referenced from pool? or they will be eligible for garbage collection along with array object.
They will not be referenced "from the pool". The references in the pool are (in effect) weak references.
They will not be eligible for garbage collection.
What is actually going to happen is that the String
objects (in the string pool) that correspond to string literals in the source code will be referenced by the code that uses the literals; i.e. there are hidden references in hidden objects that the JVM knows about. These references are what the JVM uses when you (for example) assign the string literal to something ...
It is those hidden references that mean the weak references in the pool don't break, and the corresponding String
objects don't get garbage collected.
Now, if the code that defines the literals was dynamically loaded, and the application manages to unload the code, then the String
objects may become unreachable. If that happens, they will eventually be garbage collected,
Upvotes: 4