String Pool in Java

String Pool in java is a pool of strings stored in the Java Heap Memory.String pool is a special memory storage area inside the Heap Memory. Basically ,if we create object of String class using String Literal then the object gets created inside the String pool.

String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.
When we use double quotes(String literal) to create the String object , it first looks for the String with the same value in the String pool . if it is found then it will return the reference of the same object ,else it creates a new String object in the pool and then returns the reference of newly created object.
However, using new operator, we force String class to create a new String object in heap space. We can use intern() method to put the object into the pool or refer to other String object from string pool having same value.


Example of String Pool Constant


class StringTest {

    public static void main(String[] args) {
        String str1 = "java";
        String str2 = "java";
        String str3 = new String("java");
        System.out.println("str1==str2 : " + (str1 == str2));//true,
        //str1 and str2 stores the same reference

        System.out.println("str1==str3 : " + (str1 == str3));//false,

    }
}
str1==str2 : true
str1==str3 : false

Let us understand the above example.

we have created 3 String object str1, str2, str3.
str1 : is created by string literal so the object gets created in string pool constant.
str2: now, str2 is also created by string literal but ,the object with same value ("java") is already there in string pool, so JVM returns the reference of same object and str2 also starts pointing to the same object inside string pool memory.
str3 : is created by using new keyword so a new object is created inside heap area.

Important Point

Sometimes in java interview, you will be asked question around String pool. For example, how many string is getting created in below statement.

String str = new String("Programming Language");
In the above statement, either 1 or 2 string will be created. If there is already a string literal "Programming Language" in the pool, then only one string i. e. "prgramming language" will be created in the pool. If there is no string literal "Programming Language" in the pool, then it will be created first in the pool and then in the heap space, so total 2 string objects will be created.