Master java skills

String Constant Pool vs HEAP

String Constant Pool is an area of the Heap that contains String objects created as literals (String s1 = “Arjun Kumar”).

Important Points about String Constant Pool

  1. String Constant Pool is the part of HEAP area only
  2. String objects created as literals (String s1 = “Arjun Kumar”) are stored in String Constant Pool.
  3. String Constant Pool stores only unique String objects

Now, suppose we are creating an a String object as literal.

String s1 = "Arjun Kumar";

The above line will create a reference variable called s1 and an object with value Arjun Kumar in String Constant Pool.

Let’s create another String object using literal with same value as “Arjun Kumar”

String s2 = "Arjun Kumar";

Now, since String Constant Pool only contains unique values. This means another object with value “Arjun Kumar” will not be created. Rather reference variable s2 will start pointing to the existing object “Arjun Kumar”.

String objects created in the HEAP area

Now, let’s understand how String objects are created when done using new keyword.

String s3 = new String("Shakuntala");

In the above line, the object with value “Shakuntala” is created in the HEAP area. And also, one object with value “Shakuntala” is created in String Constant Pool because there is no such object exists in there.

Let’s create one more object with value “Shankuntala” using new keyword

String s4 = new String("Shankuntala");

What will happen now? Will a new object with value “Shankuntala” be created in the HEAP area. The answer is ‘YES’.

Note -> New keyword ensures a new String object is created every time in the HEAP area irrespective of the fact whether the content is same or different.