When a String is created using the keyword new it creates a new String object using a constructor that takes a String literal. I'm wondering if the literal get stored in the constant pool before the String constructor is called.
The reason I'm asking is that in "OCA Java SE 7 Programmer I Certification Guide", Mala Gupta writes:
public static void main(String[] args)
{
String summer = new String("Summer"); //Line 1: The code creates a new String object with the value "Summer". This object is not placed in the String constant pool.
String summer2 = "Summer" //Line 2: The code creates a new String object with the value "Summer" and places it in the String constant pool.
}
She says on the first line that the String object that is created by new is not stored in the constant pool. This is fine, but what is not clear is if the literal "Summer" that goes in the constructor on the first line is.
On the second line she says that the assignment of "Summer" to summer2 stores it in the constant pool, which implies that the literal on the first line was not placed in the pool.
My Question
In short and without confusion,
You wrote ,
String summer = new String("Summer"); //Line 1: The code creates a new String object with the value "Summer". This object is not placed in the String constant pool.
That is wrong. Especially the comment >This object is not placed in the String constant pool.
The string literal "Summer" is in pool now. And the object summer
created in heap.
Does the literal "Summer" in the constructor get placed in the constant pool before the String constructor is called?
Yes. It goes to pool as it is a String literal.
Does "Summer" already exist in the pool at line 2 or is it inserted at this line?
No. Two literals are there since you are not interned. (read more about String interning)
Is the author wrong when she says that "Summer" is placed in the pool at line 2?
Other is correct with that line.
For remembrance, we can even simply say that everything between ""
goes in to pool regardless of where it is using.