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?
s1
and s2
(then s3
is created reusing s1
and s2
references)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.
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.
In Java, strings are stored in the heap area.
From Java 7 onwards, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With