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.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
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
Where the string stored.Means location of string where it stored.
- Ridham Shah
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
How come String Pool has two Cat literals and is Stringpool a part of Heap?
- Ganesh
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
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
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
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
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
Thanks. But reply form is too far from article. I can forget my answer during scrolling down )
- Timofei
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
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
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
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
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
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
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
hi pankaj, I Could not understand the following sentencecan’t undestand it . If there is already a string literal “Cat” in the pool, then only one string “str” will be created in the pool. why pool not heap? plz reply me thank you XD
- nbsaw
Hello, i have statement like as below please suggest hoe it will store in which memory, String s1 = “ABC”; String s2 = “ABC”; String s3 = s1; String s3 = new String(“ABC”); String s4 = s3;
- Mayur
Hi Pankaj, String abc = “a” + “b” + “c”; Here how many objects created in string pool memory?
- Mithun C T
On interview I was asked to explain string pool. Unfortunately I did not know answer. Its reason why I read this post. Tnx!
- Gerrix
String s1=new String(“abc”); Above line will create only one object in the heap, it won’t create two objects as you mentioned (one in heap and one in pool). To put the object in pool you need to call ‘intern()’ on this object, then it checks the pool for existence of this object in the pool, if not available then it will create one in the pool . Example : String s1=new String('abc").intern(); This will check the SCP for “abc” object, if not present then it will create this object and ‘s1’ reference will change to the SCP object and heap object will be dereferenced. Suppose if we change your code like this : String s1=new String(“abc”); s1.intern(); Then this will just create the “abc” object in SCP, but this object will not referred by the reference variable ‘s1’ (as it’s not assigned to ‘s1’). I hope it’s more clear now. Kindly comment if someone having different understanding on the same so that it will help to get correct information on the same. Kindly update the article w.r.t above details, otherwise it will give wrong impression to the reader.
- Shidram Jyoti
String s1= “old value of s1”; s1=“new value of s1”; Sysout(s1); It will give new value. Is it possible to get old value as same reference to two different literals are there.
- Purushottam
String s1 = “Hello”.concat(“World”); String s3 = new String(“HelloWorld”); //Line-2 String s2 = s1.intern(); System.out.println(s1 == s2); //false System.out.println(s1 == s3); //false System.out.println(s2 == s3); //false If I removed Line-2 and compare s1==s2, it will return true. Could anyone explain me what exactly happens in string pool after Line-2? Thanks
- salman
Hello Pankaj, Could you plea address below doubt? Lets say in my Java app I have one calss - A having method for String as setContent and getContent. Now Once I set the String Content using setter method, later I use that object of class A to get that String and put in List using getter method. where that list element will point ? to String pool or somewhere else?
- Tukaram
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. will be created in pool or heap memory(outside pool)?
- Vettaiyan
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.