- As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory.
- We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes.
- 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.

- Above diagram 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.
- 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.
public class StringPool {
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 :
s1 == s2 :true
s1 == s3 :false
Interview Question on String Class:
Question 1 :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.
Question 2: What is output:
String A = "Test";
String B = "Test";
A.toUpperCase();
System.out.println("A = " + A);
System.out.println("B = " + B);
Output :
A = Test
B = Test
If code is changes as below: A = A.toUpperCase(); Then output will be : A = TEST B = Test
