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
ands2
(thens3
is created reusings1
ands2
references)