Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 247
Jordi Castilla Avatar asked Jul 15 '16 11:07

Jordi Castilla


People also ask

How do you reuse a string in Java?

By reusable, it is meant that, when you want to use another String with exactly the same characters and encoding, a new String object is not created. Instead, the reference will point to the already existing String in the string pool. This is called interning. This can be done because String s are immutable in Java.

Can string be reused?

Simple answer: yes. However, the string or strings you reuse are going to be poorer in quality and sound than a new one. Used strings will be worn, have lost some of their tone and probably sound dull and flat.

How are strings stored internally in Java?

In Java, strings are stored in the heap area.

Is string pool garbage collected in Java?

From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.


1 Answers

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.

like image 117
Joachim Sauer Avatar answered Oct 18 '22 12:10

Joachim Sauer