String literal pool

20 January 2012 By Nithya Vasudevan 25,850 views 29 Comments
30 Flares Twitter 0 Facebook 26 Google+ 4 30 Flares ×

There are slight differences between the various methods of creating a String object. String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals/objects to increase performance and decrease memory overhead. To cut down the number of String objects created, JVM maintains a special memory called “String literal pool” or “String constant pool”.

Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool.

For example,

Direct Method of creating String object

String s1 = "iByteCode";

How this works?

  • JVM checks the String constant pool first and if the string does not exist, it creates a new String object “iByteCode” and a reference is maintained in the pool. The variable ‘s1′ also refers the same object.
  • This statement creates one String object “iByteCode”.
  • Now, let’s see what happens if we have a statement like this:
  • String s2 = "iByteCode";
  • JVM checks the String constant pool first and since the string already exists, a reference to the pooled instance is returned to s2.
  • This statement does not create any String object in the memory and ‘s2′ refers the same object as ‘s1′.
  • To check this, you can compare two String references using == operator to check whether two references are referring to the same String object in the memory.
String s1 = "iByteCode";
String s2 = "iByteCode";
if(s1 == s2)
	System.out.println("s1 and s2 referring to the same object.");

s1 and s2 referring to the same object.


Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example, if several reference variables refer to the same String object then it would be bad if any of them changes the String’s value. This is the reason for making String objects as immutable.

Creating String using constructor

String s = new String("iByteCode");

In this case, because we used ‘new’ keyword a String object is created in the heap memory even if an equal string object already exists in the pool and ‘s’ will refer to the newly created one.

String str1 = "iByteCode";
String str2 = new String("iByteCode");
System.out.println(str1 == str2);

false

String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added. For example,

String s1 = new String("iByteCode");
String s2 = s1.intern();
String s3 = "iByteCode";
System.out.println(s2 == s3);

true



In the above example, if the change the statement 2 as,

 String s2 = s1;

Reference variable ‘s2′ will refer to the string object in the heap instead of string literal pool and s1 == s2 will print true.

An object is eligible for garbage collection when it is no longer referenced from an active part of the application. In the case of String literals, they always have a reference to them from the String Literal Pool and are, therefore, not eligible for garbage collection.

All the string literals are created and their references are placed in the pool while JVM loads the class. So, even before a statement like this String s1 = new String(“iByteCode”); is executed, the string literal pool contains a reference to “iByteCode”.

Tags: , , , , , , , , ,

  • Kiran

    Really best way of explaining.Helpful for visual learners.Thank you .

    • kesava

      gud wid clear explanation.

  • jasandeep Singh

    thanks for explanation, but you get the last part of string garbage collection wrong.
    The string literals are created on heap (permgen) but do get garbage collected when unreferenced.

    • http://theopentutorials.com Praveen Macherla

      This has been extensively discussed everywhere but with no clear answer. Since the literal pool always contains a reference to the object in the heap, they would not be gc’ed unless the entire class and its loader are gc’ed which does not happen quite often.

      • Raja Rajan

        Nice question and nice answer

  • Pingback: JavaPins

  • http://myjavadiary.blogspot.in String Pool (http://myjavadiary.blogspot.in/2012/06/string-pool-purpose-of-string-pool-in.html)

    Nice post. Good presentation.

  • Abhijit

    nice post ………was really helpful…….. thks

  • senthil

    Hi,

    good explanation. Great Job.

  • http://www.gotboredreadme.com cyber

    really a very nice explanation, haven’t read anything which is so easy to understand so quickly.. I was always doubtful between string normal creation and using ‘new’..its clear now.. thanks

  • Sankar VP

    It was really nice explanation.
    Small correction in “Statement 1:” of “String literal/constant pool and intern()”

    when we create an object like String s = new String(“iByteCode”), it will create object in heap and returns the reference, it won’t create one more object for String constant pool. If that is the case then every string object which is created by using constructor should have two objects (one for reference and one for String constant pool).

    So when we call intern() method on String object, it will check whether that string already exist in String constant pool or not, If it has then return or else create new object and put that reference into String constant pool and then return.

    • Arijit

      Whenever JVM sees something within ” “, that is a literal, it adds the literal to the Constant Pool, if it not already available
      String one = new String(“abc”);// abc gets added to Constant Pool
      String two = one.intern();//two stores the reference of “abc” from the constant pool
      String three = “abc”;
      System.out.println(two == three); //true

  • Sankar

    It was really nice explanation.
    Small correction in “Statement 1:” of “String literal/constant pool and intern()”

    when we create an object like String s = new String(“iByteCode”), it will create object in heap and returns the reference, it won’t create one more object for String constant pool. If that is the case then every string object which is created by using constructor should have two objects (one for reference and one for String constant pool).

    So when we call intern() method on String object, it will check whether that string already exist in String constant pool or not, If it has then return or else create new object and put that reference into String constant pool and then return.

    • http://theopentutorials.com Praveen Macherla

      All the String literals will be added to the pool by the JVM while the class is loaded. So “iByteCode” being a literal will be added to the pool even before the String ‘s’ is constructed. That is what is depicted in the picture.

  • sarang

    If every string class object created by constructor, like
    String str2 = new String(“iByteCode”);
    is getting memory in string constant pool, than why is it also allocating the memory for same object in heap, isn’t is causing wastage of memory by placing same object at 2 different places??

    • http://theopentutorials.com Praveen Macherla

      The constant pool only contains references. Objects are always in heap. Because of String immutability it is safe for multiple references pointing to same object. So for a repeated string instead of creating a new object it refers to the already existing one thereby saving memory.

  • Sivaji

    I have a small doubt on this.
    If every string literal is added to the string pool, then what is the need of calling intern() method ?

  • Nassar

    Since every string has a reference to it from the string literal pool,
    then when these objects are eligible for garbage collection?

  • lokanadham c

    what purpose String constant pool is designed for String s=”india” or
    String s1=new String(“india”); if i am creating huge no of String objects with same content as your point view all String object are created in heap only one object in reference in string constant pool and they are different object with same content in heap then what is need of scp reply pls

  • Manish Gupta

    awesome, this is the best explanation I ever heard!!

  • http://www.facebook.com/allaudinology Qazi Allaudin

    “All the string literals are created and their references are placed in the pool while JVM loads the class. So, even before a statement like this String s1 = new String(“iByteCode”); is executed, the string literal pool contains a reference to “iByteCode”. ”
    from this part you can say that everytime when you invoke intern() method there is always a reference in string pool to the string literal of invoking object .
    so saying like “if present otherwise it is added to the pool (in diagram 4)” is pointless to me .

  • chandu

    Super……….. beautiful interpretation on strings

  • Abhijit

    @Nithya Vasudevan, Here one question By using String Concatenation operator (+) in memory where and how string object will be created.

  • John

    Great Explanation..Thanks

  • Jefferson Diefenbach

    Wonderfull explanation! Thank you so much!

  • Pingback: JVM内部细节之三:字符串及字符串常量池 | 易鸣

  • Pingback: Desempenho na criação de strings em Java | DL-UAT

  • Anuj Kumra

    Are the references stored in the literal pool or the object itself?
    In some of the posts i have gone through says when we use new keyword two objects are created one in the literal pool and one in the heap memory , nothing has been mentioned about the reference in the Pool

  • Pingback: JVM内部细节之三:字符串及字符串常量池 – JavaMiner的精神家园