Search code examples
javastringstring-interning

When to use intern() on String literals


I see a lot of legacy code like this:

class A {
    public static final String CONSTANT = "value".intern();
    ...
}

I don't see any reason for the intern(), as in the Javadoc one can read: "All literal strings and string-valued constant expressions are interned." Is there some intent of this, maybe in past revisions of the language?


Solution

  • This is a technique to ensure that CONSTANT is not actually a constant.

    When the Java compiler sees a reference to a final static primitive or String, it inserts the actual value of that constant into the class that uses it. If you then change the constant value in the defining class but don't recompile the using class, it will continue to use the old value.

    By calling intern() on the "constant" string, it is no longer considered a static constant by the compiler, so the using class will actually access the defining class' member on each use.


    JLS citations: