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

Prasad Kharkar

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.

87 thoughts on “The String Constant Pool

  • Pingback:String comparison with equals and assignment operator | theJavaGeek

  • September 26, 2013 at 11:19 am
    Permalink

    Very good explanation.

    Reply
    • September 30, 2013 at 11:53 pm
      Permalink

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

      Reply
      • July 16, 2014 at 5:51 pm
        Permalink

        Are u have some knowledge about android..??

        Reply
        • July 17, 2014 at 8:29 am
          Permalink

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

          Reply
      • August 22, 2014 at 4:14 pm
        Permalink

        You did’t mention what is string pools?

        Reply
        • July 20, 2016 at 2:19 pm
          Permalink

          String Pool is a part of heap area

          Reply
          • March 19, 2017 at 10:21 am
            Permalink

            you mean that string pool exist inside the heap area

      • February 9, 2018 at 2:46 pm
        Permalink

        Hi, just one question, would you please explain what will happen after completion of main method. ?

        are s and s2 eligible for garbage collection ?

        Reply
  • September 26, 2013 at 11:20 am
    Permalink

    Thanks for this post.

    Reply
  • November 21, 2013 at 12:27 am
    Permalink

    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)

    Reply
    • November 21, 2013 at 10:47 am
      Permalink

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

      Reply
  • November 22, 2013 at 4:20 am
    Permalink

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

    Reply
    • November 22, 2013 at 11:05 am
      Permalink

      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

      Reply
      • September 28, 2014 at 12:20 am
        Permalink

        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).

        Reply
  • November 22, 2013 at 4:25 am
    Permalink

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

    Reply
    • November 22, 2013 at 10:50 am
      Permalink

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

      Reply
  • December 5, 2013 at 11:59 am
    Permalink

    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

    Reply
    • July 28, 2015 at 6:42 pm
      Permalink

      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.

      Reply
      • April 11, 2016 at 12:34 am
        Permalink

        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…

        Reply
        • July 15, 2016 at 12:21 pm
          Permalink

          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..

          Reply
      • April 11, 2016 at 12:37 am
        Permalink

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

        Reply
  • December 10, 2013 at 4:39 pm
    Permalink

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

    Reply
    • April 9, 2017 at 12:10 am
      Permalink

      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

      Reply
  • June 24, 2014 at 9:05 pm
    Permalink

    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

    Reply
    • June 25, 2014 at 10:18 am
      Permalink

      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 🙂

      Reply
      • March 26, 2018 at 4:59 pm
        Permalink

        Hello Prasad,

        String str1=”Sachin”;
        String str2=”SachinTendulkar”;

        String str3=str1.concatenate(“Tendulkar”);

        System.out.println(“str2==str3 “+(str2==str3));

        Why it is printing false?

        Reply
  • July 20, 2014 at 1:00 am
    Permalink

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

    Reply
  • September 8, 2014 at 5:07 pm
    Permalink

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

    Reply
  • September 10, 2014 at 11:40 am
    Permalink

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

    Reply
  • November 11, 2014 at 9:30 pm
    Permalink

    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 ,

    Reply
  • November 12, 2014 at 11:21 pm
    Permalink

    Very good Explanation.thank u so much

    Reply
  • February 19, 2015 at 12:54 pm
    Permalink

    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?

    Reply
    • July 15, 2016 at 12:37 pm
      Permalink

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

      Reply
      • July 15, 2016 at 12:41 pm
        Permalink

        try comparing after: SM.toString().

        Reply
  • May 9, 2015 at 10:01 am
    Permalink

    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

    Reply
  • May 13, 2015 at 8:12 pm
    Permalink

    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 …

    Reply
  • June 12, 2015 at 7:36 am
    Permalink

    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?

    Reply
  • July 2, 2015 at 10:39 pm
    Permalink

    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

    Reply
  • July 9, 2015 at 10:52 am
    Permalink

    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???????

    Reply
    • July 28, 2015 at 6:08 pm
      Permalink

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

      Reply
      • July 28, 2015 at 6:13 pm
        Permalink

        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. */

        Reply
  • July 28, 2015 at 6:33 pm
    Permalink

    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.

    Reply
  • July 29, 2015 at 12:40 pm
    Permalink

    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.

    Reply
  • September 2, 2015 at 4:06 pm
    Permalink

    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?

    Reply
    • October 21, 2015 at 5:24 pm
      Permalink

      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…..

      Reply
  • September 27, 2015 at 2:21 pm
    Permalink

    Can please explain about grammer in java and why?

    Reply
  • October 7, 2015 at 11:34 pm
    Permalink

    Very good explanation.

    Reply
  • October 19, 2015 at 11:32 pm
    Permalink

    Nice tutorial thanks Prasad

    Reply
  • March 9, 2016 at 12:55 pm
    Permalink

    Short and good explanation.

    Reply
  • March 18, 2016 at 10:40 pm
    Permalink

    Hi,

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

    Reply
  • June 7, 2016 at 6:17 pm
    Permalink

    I read but i’m not getting….

    Reply
    • June 7, 2016 at 10:56 pm
      Permalink

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

      Reply
  • June 15, 2016 at 3:18 pm
    Permalink

    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.?

    Reply
    • June 15, 2016 at 7:51 pm
      Permalink

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

      Reply
  • June 15, 2016 at 3:29 pm
    Permalink

    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

    Reply
  • June 15, 2016 at 5:42 pm
    Permalink

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

    Reply
    • October 9, 2016 at 11:59 am
      Permalink

      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?

      Reply
      • October 10, 2016 at 8:54 am
        Permalink

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

        Reply
  • Pingback:Technical Questions Resources | webhav

  • December 5, 2016 at 11:40 pm
    Permalink

    Hi sir ,

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

    Reply
  • December 8, 2016 at 12:24 pm
    Permalink

    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,

    Reply
  • December 8, 2016 at 12:26 pm
    Permalink

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

    thanks.

    Reply
  • December 22, 2016 at 12:58 am
    Permalink

    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”

    Reply
    • December 22, 2016 at 2:43 pm
      Permalink

      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.

      Reply
      • February 8, 2017 at 11:30 pm
        Permalink

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

        Reply
  • February 13, 2017 at 1:41 pm
    Permalink

    Dear Prasad,

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

    Regards
    J.Balakrishna

    Reply
  • April 23, 2017 at 11:30 pm
    Permalink

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

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

    Reply
  • May 5, 2017 at 8:20 am
    Permalink

    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.

    Reply
  • June 30, 2017 at 11:05 am
    Permalink

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

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

    Reply
  • July 19, 2017 at 12:04 am
    Permalink

    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?

    Reply
  • November 22, 2017 at 4:25 pm
    Permalink

    Hi I have a doubt what if we are taking user input as

    String s1=sc.next();
    each time user enter a different value for s1 then what happens in this case, does address of s1 changes every time?
    please explain!!!

    Reply
  • December 7, 2017 at 11:11 am
    Permalink

    what is the difference between string pool and string constant pool???

    Reply
  • Pingback:Immutability of Strings in Java - QuestionFocus

  • February 23, 2018 at 4:11 pm
    Permalink

    How can we conclude whether String object is present in heap memory or String constant pool

    Ex: String s=new String(“Rajesh”);

    For above example considering there is no existing string literal “Rajesh” i which memory object is created how we can conclude the type of the memoty in which it is stored

    Reply
  • April 17, 2018 at 5:23 am
    Permalink

    Great. Thanks for your explanation Prasad

    Reply

Leave a Reply

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