Pregunta

Consider the code :

public class Stringer {

    public static void main(String[] args) {

        String s1 = "SomeLine";
        System.out.println(s1);  // prints SomeLine
        s1 = "AnotherLine";
        System.out.println(s1);  // prints AnotherLine
    }

}

When I change s1 from SomeLine to AnotherLine , since Strings are Immutable , does this mean that SomeLine is lost and is eligible for GC ?

Much appreciated

¿Fue útil?

Solución

When I change s1 from SomeLine to AnotherLine, since Strings are Immutable, does this mean that SomeLine 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:

Otros consejos

Yes you're right, it does become eligible for garbage collection. This is because you are no longer referencing the original string with your variable.

Here is a related question on SO:

Aren't String objects in Java immutable?

It is not that trivial when talking about Strings in Java. Even if the String is interned it can still be garbage collected. In java 6, even if it is allocated in the permgen, it can be garbage collected, in Java 7 they are allocated on the Heap and are still eligible for GC.

Usually interned Strings are not eligible for garbage collection because the class has a reference to it. But what if that class was loaded dynamically (Class.forName)? It could easily be the case when that Class could be unloaded, thus an interned string could be reclaimed by GC.

See an example here that shows that interned strings could be garbage collected.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top