1/5/15

How Many String Objects

java logo
Java String


This question is often asked. Here are some help 

Example 1:

String s1 = "abc";

How many objects it will create?
Answer : 1

Explanation:-
Here s1 is literal and it will go to String literal pool in memory. 1 object and 1 reference(s1) will get created assuming "abc" is not already present in string literal pool.

If "abc" is already present in String Literal Pool then only one reference ie s1 will get created and point to already existing "abc"


Example 2:

String s2 = new String("abc");

How many objects it will create?
Answer : 2
Explanation:-
Look in String class constructor which takes String as argument. As
 public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
// Reference from Java String Class

So as you can see here first String original will get created and one String object will get created. Then original will be assigned as value to String object. String object will be assigned to s2 reference. In the end original will be garbage collected.
Things that will be created are
a) 2 Objects :- String and original both are of String type
b) 1 Reference variable :- s2

Same as in example 1, if original already exists on String Literal pool then it will not get created.

Note : In example 2 original corresponds to abc.