Tutorial

What is Java String Pool?

Published on August 3, 2022
Default avatar

By Pankaj

What is Java String Pool?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.

String Pool in Java

Here is a diagram that clearly explains how String Pool is maintained in java heap space and what happens when we use different ways to create Strings. String Pool in Java, string pool, java string pool String Pool is possible only because String is immutable in Java and its implementation of String interning concept. String pool is also example of Flyweight design pattern. 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 the 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 another String object from the string pool having the same value. Here is the java program for the String Pool image:

package com.journaldev.util;

public class StringPool {

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

}

Output of the above program is:

s1 == s2 :true
s1 == s3 :false

Recommended Read: Java String Class

How many Strings are getting Created in the String Pool?

Sometimes in java interview, you will be asked a question around String pool. For example, how many strings are getting created in the below statement;

String str = new String("Cat");

In the above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so a total of 2 string objects will be created. Read: Java String Interview Questions

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 8, 2021

If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool? not in the heap space?

- Walker

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 14, 2020

    What Code level difference between String and StringBuffer class cause one to be immutable and other to be mutable.

    - Bhushan parakh

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      May 1, 2019

      why string object will also be stored in string pool wen it is created using new keyword…

      - ahana

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        March 20, 2019

        Hi… i think there is a small mistake in :“If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool” - if you have already literal “Cat” in the String pool then only one element will be creared in heap memory…

        - Neshi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 14, 2019

          Hey, Nice read. I have a question though. So, if I create a string object with new operator, 2 objects are created one in string pool (if already not present in string pool) and other in heap, right? So that implies while creating string object with new, string pool is checked if the literal is already present. But doesn’t intern() does the same thing? i.e check in string pool if literal already exist, if not, create new literal

          - Rhicha

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 11, 2018

            @Shidram Jyoti its correct answer, I think. String class intern method also supports this. As per intern() method, it will check first in string pool if string exists or not that means “new String(“abc”)” will not create string in string pool otherwise why “new String(“abc”).intern();” require to check string in string pool if it would have been created string when new String(“abc”).

            - Asish Bajpai

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              September 1, 2018

              e.g. “Test” has referenced by many reference variables, so if any one of them change the value others will be automatically gets affected i.e. lets say String A = “Test” String B = “Test” Now String B called, “Test”.toUpperCase() which change the same object into “TEST”, so A will also be “TEST” which is not desirable I found this on one website…please clear my doubt about this point. * I done the code but I get the original value of the A “Test” not a “TEST”. after doing uppercase

              - Dhananjay

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 29, 2018

                I appreciate it perfect ever !!!

                - Mahdi

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 24, 2018

                  String str = new String(“Cat”); It will create one String in Heap this is clear. Why it should check in String pool and if it is not there need to create one more.In this case 2 strings memory is allocated internally in the heap[String pool is also part of Heap]. Please clarify this it is confusing me.Below one atleast explain more. In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. If there is no string literal “Cat” in the pool, then it will be first created in the pool and then in the heap space, so total 2 string objects will be created.

                  - Ramesh G

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    March 28, 2018

                    “In above statement, either 1 or 2 string will be created. If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool.” Don’t you notice anything strange here? I think if there already exist one in the pool, then only one will be created only in the heep. will not it be?

                    - Hayk

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel