Search code examples
javastringjls

Are the String lliterals stored in the string pool unique?


I understand that Strings may be interned, but it it an action that is performed religiously when a new string object is created?

Jls section 3.10.5 string literals.


Solution

  • All String literals go into the string pool. Otherwise, your application must call intern() on the String, or it won't go into the pool.

    A String literal is a string that appears in source code with double quotes around it:

    String greeting = "Hello, ";
    String s = greeting + name;
    

    In this example, "Hello, " is a literal string. It is in the intern pool. It is also referenced by the variable greeting.

    The String referred to by s is not a literal, and is not in the intern pool… unless you make this call:

    s = s.intern();