String pool is like a bucket which has string constants.
For instance, Object a = new Object(); Object b = new Object(); After execution of the above statements, two objects are created and placed on heap.
But, String s1 = "abc"; String s2 = "abc"; After these two statements, only 1 object is created (on string pool). Since, they are string constant(objects).
Now, String s1 = new String("abc");
After above statement is executed, there created two objects. One object is created on heap (and referenced by 's1'). Another object is created on String pool.
The difference is: The object created on heap are garabage collectible (when they are eligible). But, The object created on string pool are never garbage collected. [ November 16, 2005: Message edited by: Mani vannan ]
How many objects would be there in the string pool....
The String pool is a collection of String objects that have been interned. String literals are automatically interned. So, when the class containing this code is loaded, a String object will be created containing the character sequence ['a','b','c'], and it will be interned. All occurrences of the literal "abc" in this code will refer to the same String object.
With the following lines, two new Strings are created and initialized with the same character sequence. These strings are not pooled.
There will be three distinct String objects created by this code, but only one of which will be pooled.
Hope this helps! [ November 16, 2005: Message edited by: Steve Morrow ]
A String object will get created in the heap and reference will be put into the String Pool. By that statement I mean to say is "Programmer wont have any control over that reference." So, whatever the program logic is, "abc" will be pointed by String Pool.
will s1 be eligible for Garbage Collection or not?
s1 is a reference variable, not an object; only objects are eligible for garbage collection. In this case, there is a single String object, referred to both by the literal and by the variable s1. Because a strong reference is held to the String object, it is not eligible for garbage collection.