What is String Pool?

String Pool

String Pool in java is a pool of Strings stored in Java Heap Memory.

String is special class in java and we can create String object using new operator as well as providing values in double quotes.

Strings in java are immutable and every new string created is stored in 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 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.

Example :

public class StringPool {

    /**
     * Java String Pool example
     * @param args
     */
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = new String("Hello");
        
        System.out.println("s1 == s2 :"+(s1==s2));
        System.out.println("s1 == s3 :"+(s1==s3));
    }

}

Output :

s1== s2 :true

s1==s3:false

Posted on by