String Constant Pool in Java

What is String Constant Pool in Java?

It is a special memory area in Heap that contains references of string objects. There are two ways to create string object in Java.

1. Using string literal

Example: String s = “java”;

A string written inside double quotes is called string literal. Whenever we create string literal the JVM checks string constant pool. If the string is already present in pool then its reference is fetched. If the string is not present in pool then a new string object is created in the pool.

2. Using new keyword

Example: String s = new String(“java”);

When we create string using new keyword it goes to heap.

 

Lets take one example to understand this.

String Constant Pool in Java

In above example total two objects are created. One in string pool and another in heap.

First JVM checks for “java” string literal in pool. As it is not present in pool so an object is create and its reference is stored in s1. Now “java” string literal is already present in pool so its reference is fetched and stored in s2. Hence s1 and s2 are pointing to same object and s1 == s2 returns true.

In third case we are creating string using new keyword so it is created in heap and its reference is stored in s3. Hence s1 and s3 are pointing to different objects and s1 == s3 returns false.

Above example shows that string literals with same value point to same object. Strings created using new keyword point to different objects.

Comment below if you found anything incorrect or missing in above tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *