The String Constant Pool

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In the previous post, we have learned about string immutability. Another interesting thing about strings in java is The String Constant Pool. So what is it exactly? It is a special place where the collection of references to string objects are placed. What makes this so special? we will try to understand it now.

In our tutorial about String immutability, we have learned that string literals cannot be modified and multiple reference variable can refer to the same string literal. Let us first write a program to understand object comparison and references

The output of the above code is

Now lets know what happens here step by step

  • The class is loaded when JVM is invoked.
  • JVM will look for all the string literals in the program
  • First, it finds the variable s which refers to the  literal “prasad” and it will be created in the memory
  • A reference for the literal “prasad” will be placed in the string constant pool memory.
  • Then it finds another variable s2 which is referring to the same string literal “prasad“.
  • Now that JVM has already found a string literal “prasad“, both the variables s and s2 wil refer to the same object i.e. “prasad“.

The diagram below demonstrates this

String literals referred

String literals referred

Now we have looked into the case when string literals are created without using the new operator. What happens if String s2 = new ("prasad"); 

As we are invoking the new keyword, The object “prasad” will be created when the new String(“prasad”) is invoked. This is unlike the string literal “prasad” which is created when class is loaded.

Now the values of objects referenced by variable s and variable s2 are the same i.e. “prasad” but those are not the same objects. They refer to different objects. We will verify this with a program

This outputs,

  • The contents of both objects are the same so equals method returns true
  • The objects referred by both variables are different so == operator returns false

This is elaborated in this diagram

String with new keyword

String with new keyword

Points to be remembered

  • String literals with same values will always refer to the same String object
  • String objects created using new operator will be different from literals

Hope this helped clarify doubts regarding string literals.

Share Button

78 comments for “The String Constant Pool

  1. sambasivarao
    September 26, 2013 at 11:19 am

    Very good explanation.

    • Prasad Kharkar
      September 30, 2013 at 11:53 pm

      Thank you for stopping by and commenting. I am glad this post was useful to you.

      • punit
        July 16, 2014 at 5:51 pm

        Are u have some knowledge about android..??

        • July 17, 2014 at 8:29 am

          Hi Punit, Currently I have not delved into android, but you can find good articles about core java, servlets, jsp and JPA here.

      • Mukesh
        August 22, 2014 at 4:14 pm

        You did’t mention what is string pools?

        • kailash
          July 20, 2016 at 2:19 pm

          String Pool is a part of heap area

          • sheetal
            March 19, 2017 at 10:21 am

            you mean that string pool exist inside the heap area

  2. sambasivarao
    September 26, 2013 at 11:20 am

    Thanks for this post.

  3. Sudhir Kumar
    November 20, 2013 at 11:44 pm

    thank you

  4. Sudhir Kumar
    November 21, 2013 at 12:27 am

    i was aware that it contains collection of String literals in Constant Pool.

    if String Constant Pool- contains collection of reference to String literals than where String literals place. (both String Object, with & without “new” keyword placed , in heap only or in constant pool also)

    • Prasad Kharkar
      November 21, 2013 at 10:47 am

      String literals are placed in constant pool. String objects created using new keyword are in heap memory.

  5. Sudhir Kumar
    November 22, 2013 at 4:20 am

    you mean both String object(with & without new keyword) references are placed in constant pool, right .

    • Prasad Kharkar
      November 22, 2013 at 11:05 am

      No, what I mean is; string objects created using literal only i.e. String s = “Sudhir” will be placed in constant pool whereas String s1 = new String(“Sudhir”); will be placed in the heap memory.

      As far as reference variables s and s1 are concerned, they will be placed in the stack of they are method local variables or in heap as a part of object(field).

      These links will guide you more.
      this and this

      • rishabh gupta
        September 28, 2014 at 12:20 am

        sir,
        please clear the concept of strings using literals and with new keyword memory wise(representation of objects creation in heap and pool by diagram).

  6. Sudhir Kumar
    November 22, 2013 at 4:25 am

    your diagram is not visible in browser(does not display)

    • Prasad Kharkar
      November 22, 2013 at 10:50 am

      I will look into the issue and solve as soon as possible.

  7. DineshPazhaniyandi
    December 5, 2013 at 11:59 am

    Hi… This Site is good and very easy to understand….

    I want to say something here.. About Strings.

    Every thing will be loaded in heap.. but when u use ‘String’ , In heap two region will be created
    1.String Constant Pool
    2.String Non Constant Pool

    when u use String=”ABC”; like this it will load to String Constant Pool.—>no duplicates
    when u use String=new String(“ABC”); like this it will load to String Non Constant Pool—> duplicates allowed

    • Rajkumar
      July 28, 2015 at 6:42 pm

      Hi Dinesh,

      I’m having a doubt now.
      Would you please clarify?

      Case 1:

      String name = new String(“Rajkumar”);

      How many objects get created and where are they created?
      My guess is two and they both created at heap and reference of string literal is stored in constant pool.

      Case 2:

      String name = “Rajkumar”;
      String name1 = new String(“Rajkumar”);

      How many objects get created and where are they created?

      Please post your reply to rajvec@yahoo.com, if possible.

      Thanks & Regards,
      Rajkumar.

      • siblee
        April 11, 2016 at 12:34 am

        in case 1 two objects are created …one in heap area and second one in string constant pool…but the reference variable pointing to heap object…

        • Avinash
          July 15, 2016 at 12:21 pm

          In case1:
          1 object will be created in the HEAP Memory. Its reference will be in STACK(main STACK or methods STACK )
          For Instance Variable –> main method STACK.
          ForLocal Variable –> method level STACK.

          Case2:
          2 Objects will be created.

          String name = “Rajkumar”;// In the CONSTANT POOL –> reference will be in STACK
          String name1 = new String(“Rajkumar”);// IN the HEAP –>reference will be in STACK

          STRING CONSTANT POOL contains the content of the String not the reference..

      • siblee
        April 11, 2016 at 12:37 am

        in case 2:
        total 2 objects are created…one in heap area and other one in scp area….

  8. December 10, 2013 at 4:39 pm

    Most confusing facts about the strings,very well explained..post bookmarked 🙂

    • Dharmendra
      April 9, 2017 at 12:10 am

      Still he didn’t cover the most import point like if you add two String into another String then what will happen if you apply equals() and == operator

  9. December 14, 2013 at 1:05 pm

    nice explanation

  10. June 24, 2014 at 9:05 pm

    Hi Prasad,

    Good to include the explanation for String.intern() method which will move the String object created using new operator to String Literal Pool.

    String str = new String(“prasad”).intern();

    now this object created using new operator will be pointed to String literal Pool.

    Thanks
    Shanky

    • June 25, 2014 at 10:18 am

      Hi Shanky, thanks for pointing it out 🙂
      I will definitely include your suggestion and update the article.
      I am glad you turned up on my site 🙂

  11. Pankaj sharma
    July 20, 2014 at 1:00 am

    Thanks sir , i get the concept properly and love the way you teach each and every thing
    properly

  12. Poovenadn Murugan
    September 8, 2014 at 5:07 pm

    I like these conversation very much 🙂
    I would like to join and learn more things with you guys 🙂 ….

  13. Krishna Thakkar
    September 10, 2014 at 11:40 am

    Really Great thing and all basic thing about string is cleared 🙂

  14. krishna
    November 11, 2014 at 9:30 pm

    HI prasad,
    That was a nice explationation,But i have one qry,How can we practically OR programitcally prove that String Obect is created at StringConstantPool.Even though we have intra() method,which will always return string object.& In diagram menthoned that the “prasad” is creted at HEAp,That abit confusion ,

  15. Nandhu
    November 12, 2014 at 11:21 pm

    Very good Explanation.thank u so much

  16. swapna
    February 19, 2015 at 12:54 pm

    i am running the below prog:

    public class StringExample {
    public static void main(String[] args) {
    StringBuffer SM = new StringBuffer (“hello”);
    System.out.println(SM);
    SM=new StringBuffer(“bye”);
    System.out.println(SM);
    String S = new String(“hello”);
    System.out.println(S);
    S=new String(“bye”);
    System.out.println(S);
    System.out.println(SM.toString()==S);
    System.out.println(SM.equals(S));

    }

    }

    output:

    hello
    bye
    hello
    bye
    false
    false

    can you explain on this how memory is allocated for the string objects and where they are stored and why System.out.println(SM.equals(S)); is returning false?

    • Avinash
      July 15, 2016 at 12:37 pm

      ITS because equals method is not overridden in StringBuffer.Class to compare the content.

      • Avinash
        July 15, 2016 at 12:41 pm

        try comparing after: SM.toString().

  17. Karthik
    May 9, 2015 at 10:01 am

    Great job Prasad , very clear and lucid explanation.

    If you find time can you please create video tutorials on Core Java , DS and Algorithms in Udemy, i am sure you can create an awesome one,
    Please offer me the same at discounted rate 🙂 🙂

    All the best and Thanks again

    Regds
    Karthik

  18. Pravat
    May 13, 2015 at 8:12 pm

    I am telling you my issue.

    Pravat p=new Pravat();
    System.out.println(p);

    //i’e it will internally call to toString() method of Object class which returns Address in Hexa form…

    String s=”Bholenath”;
    System.out.println(s)

    //Will it call to toString() method or String class.If it call toString() then how it returns Content.

    public String toString()
    {
    return this;
    }

    Please explain …

  19. Guest
    June 12, 2015 at 7:36 am

    Hi,
    string s1 = new string(“Hello”);
    string s2 = new string(“Hello”;
    system.out.println(s1.equals(s2));
    system.out.println(s1==s2);

    If the program is like this. How s1 and s2 are going to store in Heap and SCP?

  20. Shekhar
    July 2, 2015 at 10:39 pm

    Hey
    Suppose if we have
    String s1=shekhar;
    String s2=she;
    S2=she+”khar”;
    If we compare why we are geting different hashcode .
    Becos as shekhar already present in string constant pool so s1 ==s2
    Please reply with justification

  21. Deepak Ram
    July 9, 2015 at 10:52 am

    String s1=new String(“hai”);
    String s2=new String(“hai”);
    System.out.println(s1.equals(s2));
    System.out.println(s1==s2);

    what will be the output for this???????

    • Rajkumar
      July 28, 2015 at 6:08 pm

      System.out.println(s1.equals(s2)); //true
      System.out.println(s1==s2); //false

      • Rajkumar
        July 28, 2015 at 6:13 pm

        String s1=new String(“hai”); /* 2 objects get created. one is for ‘hai’ & another one is for new String and reference of the second object stored in variable s1. */
        String s2=new String(“hai”);/* only one object is created that is for new String and the reference is stored in variable s2.*/
        /* As s1 and s2 point two different object locations, == will return false. */

  22. Rajkumar
    July 28, 2015 at 6:33 pm

    Hi Prasad,

    I’ve few doubts those shake my understanding about constant pool.

    1. Does the constant pool store the actual string literals in it or literals are stored in heap and their references are stored in constant pool?
    2. If the second case is correct, then in following code,

    String name1 = “Rajkumar”;
    String name2 = “Rajkumar”;

    How does JVM identify the reference of first string object and assigns it to the second one?

    Would you please explain me, how does JVM identify the reference of string object with same literals?

    Please post your reply to rajvec@yahoo.com, if possible.

    Thanks & Regards,
    Rajkumar.

  23. Rajkumar
    July 29, 2015 at 12:40 pm

    Hi Prasad,

    String firstName = “Rajkumar”;
    String lastName = ” Gandhi”;
    String fullName = new String(firstName + lastName);

    At the end of these 3 statements, how many objects would have been created?
    3 or 4?

    Thanks in Advance.

    Regards,
    Rajkumar.

  24. Riyana
    September 2, 2015 at 4:06 pm

    Hi, thanks for the explanation.
    I had a question, so when we call upon String.valueOf(anyObject) does this create a new object or does this search for it in the String pool. Also, when we call String s = “”+object, this gives the string representation, though does this create a new object or first search for it in the String pool?

    • Logical Answer
      October 21, 2015 at 5:24 pm

      It doesn’t create a new object instead of that it hold the value of the given object as a String in temporary buffer only. So you can say it’s a literals or value for String object which need to be refer…..

  25. Ram Mididoddi
    September 27, 2015 at 2:21 pm

    Can please explain about grammer in java and why?

  26. Jagrut
    October 7, 2015 at 11:34 pm

    Very good explanation.

  27. Venkat Pasupuleti
    October 19, 2015 at 11:32 pm

    Nice tutorial thanks Prasad

  28. Ivan
    February 7, 2016 at 3:10 am

    Very good

  29. Govind
    March 9, 2016 at 12:55 pm

    Short and good explanation.

  30. Pankaj
    March 18, 2016 at 10:40 pm

    Hi,

    why java come with String pool concept when we already have new string(“xyz”) .

  31. kalyani
    April 15, 2016 at 5:56 pm

    Very good article

  32. vasu
    June 7, 2016 at 6:17 pm

    I read but i’m not getting….

    • June 7, 2016 at 10:56 pm

      Please let me know what you are not able to understand. I will definitely try to help.

  33. Harshil
    June 15, 2016 at 3:18 pm

    I have one question. When you create string object using new keyword. Does it also create copy in string constant pool ?

    Let me explain more. When you write String s = new String(“Harshil”); Now s refer to object which is in heap memory. My question is does jvm also create another copy inside String constant pool. ? Which is not referenced.?

    • June 15, 2016 at 7:51 pm

      String s = new String(“Harshil”); creates new object and s refers to object in heap memory. Your understanding is correct.

  34. Harshil
    June 15, 2016 at 3:29 pm

    Can you explain this.?

    String s = new String(“Harshil”);
    String s1 = new String(“Harshil”);
    System.out.println(s.hashCode());
    System.out.println(s1.hashCode());

    why both different objects return same hashcode value?
    Does it because both have same content ?

    o/p :
    -1933373391
    -1933373391

    • June 15, 2016 at 7:50 pm

      Meaningfully equal objects will have same hashcode value. Please refer this link. http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/

    • sudhir kumar
      October 20, 2016 at 10:19 am

      In case of String hasCode() is overridden and hasCode is calculated based on content so returning same value. Two different obj may have same hasCode . Check Wrapper obj here also hasCode is overridden so to different wrapper may have same hasCode. I hope you are able to understand.

  35. Nirja Maurya
    June 15, 2016 at 5:42 pm

    Nice explanation…
    But can u please explain internal working of String constant pool? It was asked in one of my interview question..

    • Sahar
      October 9, 2016 at 11:59 am

      Hi, i had a question, how many objects will be created in the following case:

      String s = new String(“abc”);
      String s2 = new String(“abc”);

      will we have 4 objects 2 in heap and 2 in constant pool or 1 in constant pool?

      • October 10, 2016 at 8:54 am

        2 objects in heap because of new String(); and one object in constant pool i.e. literal “abc”

  36. sagar
    December 5, 2016 at 11:40 pm

    Hi sir ,

    could you please let me know what is initial size of string pool ???

  37. December 8, 2016 at 12:24 pm

    Hi Prasad ,

    Now a days i’m preparing for OCJP ,any suggestion from your site i mean how to prepare ,how much should i spend on daily basis . reference books , dumps. please suggest me if u can.

    thanks,

  38. popat
    December 8, 2016 at 12:26 pm

    HI Prasad ,
    I have to prepare for OCJP,please suggest me how i can proceed for that.

    thanks.

  39. pragun
    December 22, 2016 at 12:58 am

    Hi, re-posting one of the comments by a user called ‘Shekhar’. I haven’t tested this out but if it is true i am interested in knowing the reason for this.

    “Hey
    Suppose if we have
    String s1=shekhar;
    String s2=she;
    S2=she+”khar”;
    If we compare why we are geting different hashcode .
    Becos as shekhar already present in string constant pool so s1 ==s2
    Please reply with justification”

    • December 22, 2016 at 2:43 pm

      Hi Pragun, as far as I remember and know, + operator will create a new string and it will be a new object, so s = “she” + “khar” will create new string object. “shekhar” string literal and newly created “shekhar” will be different objects and hence different hashcodes.

      I will come up with a more concrete answer and provide you references from official language specifications soon 🙂 I hope this gives a bit idea.

      • pragun
        February 8, 2017 at 11:30 pm

        Thanks Prasad for replying. I know it is too late to reply. But yes, it helps!

  40. February 13, 2017 at 1:41 pm

    Dear Prasad,

    by seeing your explanation . I get clear picture about that
    please post topics like collections, generics
    thank you

    Regards
    J.Balakrishna

  41. Ramesh
    April 23, 2017 at 11:30 pm

    a = “hello”;
    b=”world”;
    c = a+b;
    d = “helloworld”;

    c != d … (+ will create a new object is that only answer or any other explanation)

  42. Carol Selestin
    May 5, 2017 at 8:20 am

    Hi Prasad, Thanks for the article.
    One Question from me.
    String s = “prasad”;
    String s2 = new String(“prasad”);
    I understand both are different instances.
    My doubt is whether “prasad” will be created twice.
    My understanding is “prasad” will be created only once in String constant pool and both s and s2.value(please refer below on value) will refer same “prasad” in String constant pool.

    in new String(“prasad”) , “prasad” is passed onto constructor of string like below.

    public String(String value){
    this.value = value;
    }

    So anyhow it will be assigned finally like:
    this.value = value; which is like String s = “prasad”;

    So, my understanding is “prasad” will be created only once in String constant pool though there will be two instance because of the String instance created with new operator.
    Please clarify me on this.

  43. Chethan
    June 30, 2017 at 11:05 am

    Does this still apply in Java 8…
    String s1 = “Prasad”;
    String s2 = “Prasad”;

    System.out.println(s1==s2);// will return false in Java 8

  44. wtb06
    July 19, 2017 at 12:04 am

    String b1 = new String(“bike”);
    String b2 = b1.intern();
    System.out.println( b1 == b2 ); // false

    Why does the above return false?
    Instead of return b1, does b1.intern() create another string object and put into the string pool?

  45. September 21, 2017 at 10:55 pm

    I have written an article with some insights here on the topic

    http://www.devdummy.com/2017/09/what-is-java-string-pool.html

    Hope this helps.

Leave a Reply

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