String pool and heap storage


Like many Java objects, all String instances are created on the heap, even literals. When the JVM finds a String literal that has no equivalent reference in the heap, the JVM creates a corresponding String instance on the heap and it also stores a reference to the newly created String instance in the String pool. Any other references to the same String literal are replaced with the previously created String instance in the heap.

Let's look at the following example:

class StringComparison
{
	public static void main(String[] args)
	{
		String first = "programming";
		String second = "programming";
		String third = new String("programming");
 
		// Checking if all three strings are equivalent
		boolean allAreEqual = first.equals(second) && second.equals(third);
		System.out.println("Are all strings equivalent? " + allAreEqual);
 
		// Checking if the references for 'first' and 'second' are the same
		boolean referenceEquality = first == second;
		System.out.println("Do 'first' and 'second' have the same reference? " + referenceEquality);
 
		// Checking if 'first' and 'third' have different references
		boolean differentReferences = first != third;
		System.out.println("Do 'first' and 'third' have different references? " + differentReferences);
 
		// Checking if 'second' and 'third' have different references
		boolean secondThirdDifferentReferences = second != third;
		System.out.println("Do 'second' and 'third' have different references? " + secondThirdDifferentReferences);
	}
}

The output of the above is:

Are all strings equivalent? true
Do 'first' and 'second' have the same reference? true
Do 'first' and 'third' have different references? true
Do 'second' and 'third' have different references? true
 

When we use double quotes to create a String, it first looks for String with same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference.

However using new operator, we force String class to create a new String object in heap space. We can use intern() method to put it into the pool or refer to other String object from string pool having same value.

The String pool itself is also created on the heap.

Basic Programs