Java Reference
In-Depth Information
String Literals and the String Pool
The
new
keyword is not required for creating the
String
object
“How are you?”
because
it is a string literal. String literals get special treatment by the JVM. Behind the scenes,
the JVM instantiates a
String
object for
“How are you?”
and stores it in the
string pool
.
The
greeting
reference refers to this
String
object in the pool. Because
String
objects
in Java are
immutable
(which means they cannot be changed), the JVM can optimize the
use of string literals by allowing only one instance of a string in the pool. For example,
the following two
String
references actually point to the same string in the pool, as
shown in the following diagram:
String s1 = “New York”;
String s2 = “New York”;
The String pool
s1
“New York”
s2
You might think if the two references point to the same object, then changing one object
would inadvertently change the value of the other. But
String
objects are immutable, so
the following statement only changes
s2
:
s2 = “New Jersey”;
The reference
s2
now points to
“New Jersey”
, but
s1
still points to
“New York”
, as shown
in the following diagram:
The String pool
s1
“New York”
“New Jersey”
s2
Search WWH ::
Custom Search