Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constant Pool and Non-Pool strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constant Pool and Non-Pool strings" Watch "Constant Pool and Non-Pool strings" New topic
Author

Constant Pool and Non-Pool strings

Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
I know that strings have a special area called String Constant Pool set aside from them. Hence, if you have

String s1 = "Hello";
Hello is placed in the pool. If i again need a String s2 as

String s2 = "Hello";
It is detected that Hello already exists in the pool and s2 points to the same object. This is done for the conservation for memory.

Now my question is this: If i say

String s3 = new String("Hello");

s3 will not point to the "Hello" in constant pool, instead it will be newly allocated in the non-pool memory and a new entry "Hello" (if it doesen't exist already in pool) will be added. Why is the aforementioned principle of memory conservation not applied here?
[ May 03, 2006: Message edited by: Aniket Patil ]

SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
Nidhi Jain
Ranch Hand

Joined: Mar 26, 2006
Posts: 31
b'coz here we are creating a object of String class....and all the object are stored in Heap.
Alberto Cancello
Greenhorn

Joined: Apr 27, 2006
Posts: 5
1 String s1 = "Hello";
2 String s2 = "Hello";
3 String s3 = new String("Hello");


There are:

a) In the String pool, one string "Hello". It is referenced by s1 and s2. Also a reference to it is passed to the constructor of the String in line 3.

b) An object String in the Heap, created at line 3. s3 referred to it.

Bye,
Alberto
gurpreet singh
Ranch Hand

Joined: Apr 07, 2006
Posts: 38
1 String s1 = "Hello";
2 String s2 = "Hello";
3 String s3 = new String("Hello");
4 String s4 = new String("Hello");

what happens with s4?
Will it point to s3 or new object will be created


SCJP
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
It will create a new string for s4.
Shaliey Gowtham
Ranch Hand

Joined: Mar 20, 2006
Posts: 104
All the string objects are placed only on the heap,even the String literals.
When you say

One object is created in the heap, and an entry is made in String pool to refer to the string object created in the pool.
Now there are two references to the "Hello" object,
*)in reference variable str1
*)in String pool
So there are really no object created in the String pool ever, only the references to the String literals in the heap that are known at the compile time are stored in the String pool.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constant Pool and Non-Pool strings