Search code examples
javastringspecificationseffective-java

How does the JVM reuse interned String substrings?


I'm aware if you make

for (condition) {
    String s = "hi there";
}

Just one String instance is created in all the iterations, unlike String s = new String("hi there"); that will create a new instance in each iteration.

But, reading Effective Java from Joshua Bloch: Chapter 2 Item 5 (page 20) it states:

Furthermore, it is guaranteed that the object will be reused by any other code running in the same virtual machine that happens to contain the same string literal [JLS, 3.10.5].

AFAIK that does not say happens to be the same string literal, it says contains.

Reading [JLS, 3.10.5] cannot find any exact reference to this and I have a doubt.

Giving this snippet:

String s1 = "hi ";
String s2 = "there";
String s3 = "hi there";

How many instances are created?

  • 3 instances (thus, phrase is not really exact).
  • 2 instances, s1 and s2 (then s3 is created reusing s1 and s2 references)

Solution

  • The JLS does not guarantee any reuse of sub-strings whatsoever. The "contain" here is just meant that the class mentions the exact same string literal somewhere. It is not used in the "substring of" sense.