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.
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 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
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.
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.
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
String Pool only contains reference to the String objects. The text means the same thing.
- Pankaj
Hi Pankaj, so do you mean that String pool only contains reference to string but not actual value/string ?
- Abhi
You are contradicting yourself here. First you said String objects live in the pool, now you say only the references do. So where do the objects (values) they reference to live ? In your image you have the actual values inside the pool.
- rojaja
Yes, Pankaj. Please update this post accordingly. Your other posts also say so.
- Rishi Raj
Where the string stored.Means location of string where it stored.
- Ridham Shah
Could you post some example on intern() method.
- siddu
https://stackoverflow.com/questions/17489250/how-can-a-string-be-initialized-using/17489410#17489410
- Vikash
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
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
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
Hi Ganesh, I have two questions :- 1) Why the below line is returning false, It should return true because when str4 will create than first it will check in string pool whether any other string value is present or not with the same value. If str1 is already there with the same value than it should refer the same reference as str1 has. System.out.println(str1 == str4); // returns false 2) In your above example “intern” method you are using for string pool as str4.intern(). Can we use “intern” method for string pool also?
- Mahrshi
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
How come String Pool has two Cat literals and is Stringpool a part of Heap?
- Ganesh
Corrected the image, yes String Pool is part of Java Heap memory.
- Pankaj
String str1 = “abc”;//reference is checked on constant pool String str2 = new String(“abc”);//reference is checked on heap System.out.println(str1 == str2);//returns false //that is why we use intern str2 = str2.intern(); System.out.println(str1 == str2);//return true as both are pointing to string pool //String pool is a part of constant pool and memory is getting allocated in Method Area whereas when we use new operator memory is getting allocated in heap. //Note: Methos area can be a part of heap or a seperate memory area. this depends on JVM implementation.
- Ganesh Rashinker
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
You need to write
b = b.intern();
, see you haven’t updated the reference of “b” variable.- Pankaj
intern() method return a String . but in case of you does not hold return of intern ().
- vinod
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
will be creating the new object in the string pool,
- krishna
If it is creating in the pool, then the following code should output “True”. But it is not? String str1 = “abc”; str1 = str1.concat(“d”); if(str1 == “abcd”) System.out.println(“True”);
- Maaniccka Poonkundran
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
“== result:” + s1==s2
+ operator priority is more, so it will result in"== result:India"=="India"
and hencefalse
. I hope it will clear your confusion.- Pankaj
to get the desired result you can write: System.out.println(“== result:” + (s1==s2) );
- balinder
Thnx for the post. helped to clarify a lot of things
- balinder
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
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
s3 and s4 will be referencing to two different objects. == checks if reference is same, that’s why s3==s4 is false.
- Pankaj
If s1 & s3 “Cat” objects are created in Heap & SCP area respectively and (s1==s3) returning false that is correct but why their hascodes are same then? If hashcodes are same means both references are pointing to same object then (s1==s3) should have returned true ideally? Please clarify on this. public static void main(String[] args) { String s1 = new String(“Cat”); String s3 = “Cat”; System.out.println(s1.hashCode() + " && " + s3.hashCode()); } O/P : 67510 && 67510 Regards, Vishal
- Vishal Nikam
Pankaj, Is there any way to get the size of String Pool?
- Pradeep Singh
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
When you write String s=“abc” at this point s refers to string whose value is “abc”. When you write s=s+“def” a new string “abcdef” is created and s now refers to this new string and not to “abc”. Hence originally created “abc” string remains unchanged. It remains as it is in pool.Hence strings are called immutable.
- Sarika
Thanks. But reply form is too far from article. I can forget my answer during scrolling down )
- Timofei
Reply form after comments, so that people can read others comments first. Chances are you will find your queries answered in some of the comments, saves time.
- Pankaj
Timofei, ever heard of Ctrl+End ? It will take you directly to the end of the page
- rojaja
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
4
- saroj
7 objects 1.”cat” 2.”c” 3.“at” 4.new String(“cat”); 5."kitty” 6.“kittycat” 7.new String(kittycat)
- Biswajit sahoo
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
String Pool contains String objects, remember that ‘reference’ variables always part of Stack memory, so obviously it can’t be in string pool that is part of heap memory.
- Pankaj
Nice explanation Pankaj…
- Dhananjay
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
Dear Ravi, This is where “==” and .equals differ. “==” checks equality for hash code of objects reference while .equals compares their contents. Pls let me know if u have any confusion.
- varun
You used the String equal() with a char[] array. char[] arrays are Object not String. This “newStr.equals(myStr)” compares a String with an array. When comparing 2 objects for “Equal” they should be of the same class. The equal method takes an Object but the methods usually make an instanceof check, cast to a specific type then compare the “this” with the “argument”. The rule of tumb for equal on the Java objects is: instanceof, cast then compare object internals. Of course you can implement any freaky equal but in general you should stick to the “contract” if you would have done: newStr.equals(new String(myStr)) it would have worked because it makes a new String object out of the array and the object passed to the method is a String in this case.
- Adrian
Hi Teo, If concatenate variable, so here hashcode always will be different. newStr, ch is variable. You must need to concatenate direct literal only, instead of variable means… newStr = ‘g’+“ood”; result would be ‘true’. ‘g’ and “ood” is literal. I think it not possible in loop.
- Deepak
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
Good question. Anyone have explanation?
- Anjani
it creates a reference in pool for feature used.
- saroj
String s=new String(“abc”);—-creates a string object “abc” with reference ‘s’ only in heap memory and not in string pool.
- Ajinkya Rane
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
great pictrue
- shellbye
Does String pool has divided into parts like constant pool and non-constant pool?
- Manjunath
class ClassM2{ public static void main(String[] args){ String s2 = “test”; String s3 = “test”; String s4 = s3+“”; System.out.println(s2==s3); System.out.println(s3==s4); } } Why s3==s4 gives “false”? I know “test” string stores in String pool and s2 & s3 points to same reference. but why not s4? It also has value “test”. Please explain.
- Hiren Mistry
question-Runtime constant pool and String pool are same thing or different ?
- Prashant Gawande
My idea is that if an object is in heap like this String s1=new String(“hello”); and let us say s1 holds address 123 then i do this, s1.intern(); still now s1 address 123 and holds the object “hello” in 123 However one more String object “hello” (literal object) has been created whose reference is lets say 321. Now this reference is being stored in the constant pool table. Am I correct?
- Mayank Bhandari
I have trouble understanding your following statement: String str = new String(“Cat”); 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. If you do not intern str how could a string literal be created in the string pool? If you do and the “Cat” literal does not already exists in the pool, it will only be created in the pool not on the heap. If you have something like this: String str = new String(“Cat”).intern(); then 0 or 1 string will be created depending on whether a “Cat” literal exists. Thanks, Jun
- Jun Zhuang
nice tutorials
- Deepak Kumar Sahu
Is string pool part of heap. I thought it was part of method area which is actually different from heap. The first diagram shows it as a part of heap above.
- Amol Aggarwal
When I create a String object with New operator and then use Intern() method, If String value not in Pool then add if exist in Pool then returned back reference. But what happens to the first memory created with New String(“test”)? (In Heap and outsize of Pool)
- Mohamad
hi pankaj, does StringBuffer also places object in string pool? StringBuffer sb=new StringBuffer(“abc”) how many objects are created with above line
- shravan