Reputation: 364
When a String is created using the keyword new it creates a new String object using a constructor that takes a String literal.
Does the literal get stored in the constant pool before the String constructor is called?
String hello = new String("Hello");
String literal = "Hello"; //Does "Hello" already exist in the pool
//or is it inserted at this line?
EDIT
In "OCA Java SE 7 Programmer I Certification Guide", Mala Gupta writes:
public static void main(String[] args)
{
String summer = new String("Summer"); // The code creates a new String object with the value "Summer". This object is not placed in the String constant pool.
String summer2 = "Summer" // 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 interned.
Upvotes: 2
Views: 184
Reputation: 3502
String ob1 = new String("Hello");
String ob2 = "Hello";
First line first seeks a "Hello" string
in String Pool, if it is there it creates same in Heap and our ob1 refers to that heap object. If it is not there it creates same in Pool also and in this case also, ob1 refers to heap object.
Second line also seeks for "Hello" object
in pool if its found ob2 will refer to that pool object. If not found it will create only in Pool and ob2 will refer to that pool object.
But second line never creates an String object in heap. String objects kept in String Pool are reusable but String objects created in heap are not.
Upvotes: 0
Reputation: 8652
When you write "Hello"
in your code, this String is created during compilation.
so actually its already there since you also used it to create your new String("Hello");
with the "Hello"
in it.
in conclusion: Yes.
Upvotes: 1
Reputation: 121998
Regardless of where you are using, all string literals saves in String pool. So the answer is YES.
String hello = new String("Hello");
>--------< goes to pool.
But the thing is that the h2
won't refer from that h
:)
Upvotes: 5