When I change
s1
fromSomeLine
toAnotherLine
, since Strings are Immutable, does this mean thatSomeLine
is lost and is eligible for GC?
The fact that String
is immutable is irrelevant to your question. The fact that you are reassigning the variable and therefore losing the other reference is what determines if the object is a candidate for GC or not.
To answer the question, it would be if it wasn't a String
literal.
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method
String.intern
.
That String
object won't be garbage collected because the ClassLoader
and the corresponding class have a reference to it.
Related reading: