String s = "abc"; // creates one String object and one
// reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,
// and one reference variable
In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool.
SCJP 6
Punit Singh wrote:
Can anybody clear the doubt how many objects should be created when String s = new String("abc"); is called ?
Punit Singh wrote:
and when we do String s="abc"; then "abc" is created on heap or constant pool?
[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
SCJP 6
Punit Singh wrote:
Can anybody clear the doubt how many objects should be created when String s = new String("abc"); is called ?
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
if we have
String t="abc"
String s1=new String("abc"), then this line creates just one object on heap referred to be s1,as one "abc" is already there on the heap whose reference is in the pool already.
It means if we create String like
String s=new String("abc");
and if there is not already "abc" String object in heap, then two objects are created, one of "abc" will have reference in pool and another one is referred by s.
SCJP 6
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals.When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table.
SCJP 6
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
SCJP 6
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
Punit Singh wrote:Thanks, now everything goes into mind, but one thing is contrary that K&B book says the literal "abc" will be placed in the pool. I think here literal means reference of "abc". As "abc" will be created on the heap only.
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
SCJP 6
SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
All code in my posts, unless a source is explicitly mentioned, is my own.