Sahil Rally wrote:Reference :- SCJP 6 k&b pg 434
It is written that,
String s= "abc" ;//Line 1 //creates one strig object .
In this simple case , "abc" will go in the pool and s will refer to it.
String s = new String("abc"); //Line 2 // creates two string objects
One object in non-pool memory
Another one in Pool memory
I have following two questions
Q1:- Why an object is also placed in a pool memory.
Q2:- As said by k&b that line 2 would create 2 objects in which one of them will go into pool, but after line 1 we have "abc" already in the pool, then why one more. Or the two statements are independent of one another.
yes the two statements are independent of one another
you will understand by this example
when you do
then since these two strings have same character sequence so only one string object is shared by all string valued constant expressions.Such strings are said to be interned ,i.e they they share a unique string object if they have the same content,and the String class maintains a private pool where such strings are interned.
Now,let us take
This constructor creates a new String object and therefore it does not intern the string i.e it will not share the same value as shared by a and b.
and if you do
but i dont know whether another object goes into pool ,and if it goes then it would have printed true in above code ,but it doesnt.