Tutorial

What is Java String Pool?

Published on August 3, 2022
author

Pankaj

What is Java String Pool?

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 our products

About the author(s)

Category:
Tutorial
Tags:

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 18, 2013

hi … excellent post … one correction - “we force String class to create a new String object and then place it in the pool.” here, new operator creates object in Java heap, not in pool.

- abhay agarwal

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
April 14, 2013

String Pool only contains reference to the String objects. The text means the same thing.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 20, 2013

    Yes, Pankaj. Please update this post accordingly. Your other posts also say so.

    - Rishi Raj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 1, 2013

      Where the string stored.Means location of string where it stored.

      - Ridham Shah

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 9, 2013

        Could you post some example on intern() method.

        - siddu

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 4, 2014

          I have one confusion, when we create a new String Object like String s = new String (“abc”); As far as I know, this will create a new String Object in Heap and also abc will go in String constant pool and s will point value exists in string constant pool… which means the value already exists in String Constant Pool, so what will intern do in this case? Also String Constant Pool is not a part of Java Heap Memory…?

          - kunal

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 6, 2014

          When we use new keyword to create the String object, it doesn’t go into the String Pool. When we call intern method, then it checks if any String with same value is already present in the pool or not. If there is already a String with same value, it returns the reference or else it places the String into the pool.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 7, 2014

            Hi Kunal, you can refer below snippet String str1 = “abc”; String str2 = “ab”; String str3 = “c”; String str4 = str2 + str3;//using StringBuilder for concatenation and returns new String object System.out.println(str1 == str4); // returns false str4 = str4.intern(); System.out.println(str1 == str4); // returns true

            - Ganesh Rashinker

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 20, 2015

              in frist question You are Right. when we create String by new keyword then one will go to heap and another in String pool String constant pool is depend on the JVM. architecture

              - vinod

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 4, 2014

                How come String Pool has two Cat literals and is Stringpool a part of Heap?

                - Ganesh

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 4, 2014

                Corrected the image, yes String Pool is part of Java Heap memory.

                - Pankaj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 13, 2014

                  String s = “ashish”; String b = new String(“ashish”); b.intern(); System.out.println(s==b); if string pool is manged then why not string ‘s’ reference is returned on b.intern() to b. It is printing false which means their reference are not same.

                  - Ashish

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 13, 2014

                  You need to write b = b.intern();, see you haven’t updated the reference of “b” variable.

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 20, 2015

                    intern() method return a String . but in case of you does not hold return of intern ().

                    - vinod

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      September 11, 2014

                      If for example: String str1 = “abc”; String str2 = new String(“def”); Then, Case 1: String str3 = str1.concat(str2) will go in the heap or pool? Case 2: String str4 = str2.concat(“HI”) will go in the heap or pool?

                      - krishna

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 11, 2014

                      will be creating the new object in the string pool,

                      - krishna

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        October 4, 2014

                        public class MainDemo { public void comp() { String s1=“India”; String s2=“India”; String s3=new String(“India”); System.out.println(“== result:” + s1==s2); // false System.out.println(“equals result:” + s1.equals(s2)); // true System.out.println(“****************”); System.out.println(“== result:” + s1==s3); // false System.out.println(“equals result:” + s1.equals(s3)); // true } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MainDemo obj=new MainDemo(); obj.comp(); } } Question - what is the difference between s1==s2 and s1==s3 , => both returns same result. but in your post s1==s2 is true that is not right result. I have checked this by writing same program in to this post. So plz clear my doubt ??

                        - sanjaya verma

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        October 4, 2014

                        “== result:” + s1==s2 + operator priority is more, so it will result in "== result:India"=="India" and hence false. I hope it will clear your confusion.

                        - Pankaj

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          November 3, 2014

                          Thnx for the post. helped to clarify a lot of things

                          - balinder

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            November 4, 2014

                            In the name of god. public static void main(String[] args) { String s1 = “Cat”; String s2 = “Cat”; String s3 = new String(“Cat”); String test; System.out.println(“s1 == s2 :”+(s1==s2)); System.out.println(“s1 == s3 :”+(s1==s3)); } hi, how to return value(No address) from heap(s3) to stack(test). Thanks.

                            - Amir hossein

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              December 30, 2014

                              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”; // here s1 & s2 value Cat stored into String Constant pool only once, so no doubt. String s3 = new String(“Cat”); String s4 = new String(“Cat”) ; // my question is here. here s3 & s4 value Cat is two times created into normal pool or only once created into normal pool. System.out.println(“s1 == s2 :”+(s1==s2)); System.out.println(“s1 == s3 :”+(s1==s3)); System.out.println(“s3 == s4 :”+(s3==s4)); // here both value of hashCode same but why to be false? } }

                              - Karuppasamy

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                February 12, 2015

                                Pankaj, Is there any way to get the size of String Pool?

                                - Pradeep Singh

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  February 19, 2015

                                  String s=“abc”; s = s+“def”; System.out.println("String Result:- "+s);//output - String Result:- abcdef In this case content of ‘s’ variable is getting changed but according to java concept String is immutable. So,can you please explain me what happen with ‘s’ variable in the string pool?

                                  - Pranita W

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    March 4, 2015

                                    Thanks. But reply form is too far from article. I can forget my answer during scrolling down )

                                    - Timofei

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      March 30, 2015

                                      Hi , Can you please clarify me, how many objects will be created in below case and why? String s1=“cat”; String s2=“cat”; String s3=“c”+ “at”; String s4= new String(“cat”); String s5=“kitty” + “cat”; String s6= new String(kittycat); Thanks In Advance. :)

                                      - Satish

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        April 2, 2015

                                        Hi Pankaj, I am following you articles and finding it really precise. Really appreciate your efforts. But coming to this article, I have one doubts. The value in the String pool are “String” or reference to the String Object created in the Heap i.e. collection of references to String objects ?

                                        - Ravi

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          July 12, 2015

                                          Hi, I have one example which I found a little confusing. I understand that in context of String object type, by using NEW word, new object is created and when using “” in String initialization, String pool mechanizm is used. Why isn’t String pool used in following case? *******************         String myStr = “good”;        char[] myCharArr = {‘g’, ‘o’, ‘o’, ‘d’ };         String newStr = “”;         for(char ch : myCharArr){             newStr = newStr + ch;          }         boolean b1 = newStr == myStr;          boolean b2 = newStr.equals(myStr);                   System.out.println(b1+ " " + b2); (false true is printed) ******************* Thx in advance, Teodor

                                          - Teo

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            September 2, 2015

                                            String s=“abc” ;-----creates a string object “abc” with reference ‘s’ in string pool. String s=new String(“abc”);----creates a string object “abc” with reference ‘s’ in heap memory and also creates a string object “abc” in string pool without reference so here two objects are created then what is the necessity for creating String object using new operator?

                                            - muni

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              September 17, 2015

                                              Another thing about the Java String Pool. For long term maintenance of your code you should use the “equals” method not the “==”. You may refactor the code and string pool object is replaced with a heap object and you get all kinds of problems. Refactor tools don’t “see” the cases where == should be changed to equal. primitive => == objects => equals

                                              - Adrian

                                                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!

                                                Become a contributor for community

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

                                                DigitalOcean Documentation

                                                Full documentation for every DigitalOcean product.

                                                Resources for startups and SMBs

                                                The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                Get our newsletter

                                                Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                New accounts only. By submitting your email you agree to our Privacy Policy

                                                The developer cloud

                                                Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                Get started for free

                                                Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                *This promotional offer applies to new accounts only.