I am all confused after reading the article on javaranch site by Corey McGlone, The author of The SCJP Tip Line. named Strings, Literally and the
SCJP Java 6 Programmer Guide by Kathy Sierra (co-founder of javaranch) and Bert Bates.
I will try to quote what Mr. Corey and Ms Kathy Sierra have quoted about String Literal Pool.
1. According to Mr Corey McGlone :
-
String Literal Pool is a Collection of references that point to the String Objects.
-
String s = "Hello";
(Assume there is No object on the Heap named "Hello"),
will create a String object"Hello"
on the heap, and will place a reference to this object in the String Literal Pool (Constant Table) -
String a = new String("Bye");
(Assume there is No object on the Heap named "Bye",new
operator will oblige the JVM to create an object on the Heap.
Now the explanation of "new"
operator for the creation of a String and its reference is bit confusing in this article, so I am putting the code and
explanation from the article itself as it-is below.
public class ImmutableStrings
{
public static void main(String[] args)
{
String one = "someString";
String two = new String("someString");
System.out.println(one.equals(two));
System.out.println(one == two);
}
}
In this case, we actually end up with a slightly different behavior because of the keyword "new."
In such a case, references to the two String literals are still put into the constant table (the String Literal Pool),
but, when you come to the keyword "new,"
the JVM is obliged to create a new String object at run-time,
rather than using the one from the constant table.
Here is the diagram explaining it..
So does it mean, that String Literal Pool too has a reference to this Object ?
Here is the link to the Article by Corey McGlone
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
2. According to Kathy Sierra and Bert Bates in SCJP book:
-
To make Java more memory efficient, the JVM set aside a special area of memory called the "String constant pool", when the compiler
encounters a String Literal, it checks the pool to see if an identical String already exists or not. If not then it creates a
new String Literal Object. -
String s = "abc";
// Creates one String object and one reference variable….that's fine, but then I was confused by this statement:
-
String s = new String("abc")
// Creates two objects, and one reference variable.It says in the book that…. a new String object in normal(non-pool) memory , and "s" will refer to it… whereas
an additional literal "abc" will be placed in the pool.The above lines in the book collide with the one in the article by Corey McGlone.
-
If String Literal Pool is a collection of references to the String object as mentioned by Corey McGlone, then why wil the literal object "abc" be placed in the pool (as mentioned in the book)?
-
And where does this String Literal Pool reside?
-
Please clear this doubt, though it won't matter too much while writing a code, but is very important from the aspect of memory management, and
thats the reason I want to clear this funda.
Best Answer
I think the main point to understand here is the distinction between
String
Java object and its contents -char[]
under privatevalue
field.String
is basically a wrapper aroundchar[]
array, encapsulating it and making it impossible to modify so theString
can remain immutable. Also theString
class remembers which parts of this array is actually used (see below). This all means that you can have two differentString
objects (quite lightweight) pointing to the samechar[]
.I will show you few examples, together with
hashCode()
of eachString
andhashCode()
of internalchar[] value
field (I will call it text to distinguish it from string). Finally I'll showjavap -c -verbose
output, together with constant pool for my test class. Please do not confuse class constant pool with string literal pool. They are not quite the same. See also Understanding javap's output for the Constant Pool.Prerequisites
For the purpose of testing I created such a utility method that breaks
String
encapsulation:It will print
hashCode()
ofchar[] value
, effectively helping us understand whether this particularString
points to the samechar[]
text or not.Two string literals in a class
Let's start from the simplest example.
Java code
BTW if you simply write
"ab" + "c"
, Java compiler will perform concatenation at compile time and the generated code will be exactly the same. This only works if all strings are known at compile time.Class constant pool
Each class has its own constant pool - a list of constant values that can be reused if they occur several times in the source code. It includes common strings, numbers, method names, etc.
Here are the contents of the constant pool in our example above.
The important thing to note is the distinction between
String
constant object (#2
) and Unicode encoded text"abc"
(#38
) that the string points to.Byte code
Here is generated byte code. Note that both
one
andtwo
references are assigned with the same#2
constant pointing to"abc"
string:Output
For each example I am printing the following values:
No surprise that both pairs are equal:
Which means that not only both objects point to the same
char[]
(the same text underneath) soequals()
test will pass. But even more,one
andtwo
are the exact same references! Soone == two
is true as well. Obviously ifone
andtwo
point to the same object thenone.value
andtwo.value
must be equal.Literal and
new String()
Java code
Now the example we all waited for - one string literal and one new
String
using the same literal. How will this work?The fact that
"abc"
constant is used two times in the source code should give you some hint...Class constant pool
Same as above.
Byte code
Look carefully! The first object is created the same way as above, no surprise. It just takes a constant reference to already created
String
(#2
) from the constant pool. However the second object is created via normal constructor call. But! The firstString
is passed as an argument. This can be decompiled to:Output
The output is a bit surprising. The second pair, representing references to
String
object is understandable - we created twoString
objects - one was created for us in the constant pool and the second one was created manually fortwo
. But why, on earth the first pair suggests that bothString
objects point to the samechar[] value
array?!It becomes clear when you look at how
String(String)
constructor works (greatly simplified here):See? When you are creating new
String
object based on existing one, it reuseschar[] value
.String
s are immutable, there is no need to copy data structure that is known to be never modified.I think this is the clue of your problem: even if you have two
String
objects, they might still point to the same contents. And as you can see theString
object itself is quite small.Runtime modification and
intern()
Java code
Let's say you initially used two different strings but after some modifications they are all the same:
The Java compiler (at least mine) is not clever enough to perform such operation at compile time, have a look:
Class constant pool
Suddenly we ended up with two constant strings pointing to two different constant texts:
Byte code
The fist string is constructed as usual. The second is created by first loading the constant
"?abc"
string and then callingsubstring(1)
on it.Output
No surprise here - we have two different strings, pointing to two different
char[]
texts in memory:Well, the texts aren't really different,
equals()
method will still yieldtrue
. We have two unnecessary copies of the same text.Now we should run two exercises. First, try running:
before printing hash codes. Not only both
one
andtwo
point to the same text, but they are the same reference!This means both
one.equals(two)
andone == two
tests will pass. Also we saved some memory because"abc"
text appears only once in memory (the second copy will be garbage collected).The second exercise is slightly different, check out this:
Obviously
one
andtwo
are two different objects, pointing to two different texts. But how come the output suggests that they both point to the samechar[]
array?!?I'll leave the answer to you. It'll teach you how
substring()
works, what are the advantages of such approach and when it can lead to big troubles.