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!
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.