What is string pool?

The String Pool is a special area in the Java Heap Memory where the JVM stores string literals. Its primary purpose is to optimize memory usage by reusing existing String objects instead of creating duplicate objects with the same value.

Key Points: • String literals are stored in the String Pool to reduce memory consumption. • Before creating a new string literal, the JVM checks whether the same value already exists in the pool. • If the string is found, the existing reference is returned instead of creating a new object. • String objects created using the new keyword are stored in normal heap memory, not directly in the String Pool. • The intern() method can be used to add a string to the pool or retrieve its pooled reference.

Example: If multiple variables contain the string literal "Java", the JVM stores only one copy in the String Pool and all variables reference the same object.

Code Example:

public class Demo {

    public static void main(String[] args) {

        String str1 = "Java";
        String str2 = "Java";

System.out.println(str1 == str2); // true

String str3 = new String("Java"); System.out.println(str1 == str3); // false

System.out.println(str1.equals(str3)); // true

    }
}

Memory Representation:

String str1 = "Java";
String str2 = "Java";

• Only one "Java" object exists in the String Pool. • Both str1 and str2 point to the same object.

Interview Tip: A concise interview answer is:

"The String Pool is a special memory area inside the heap where Java stores string literals. Before creating a new string literal, the JVM checks the pool and reuses an existing object if the same value already exists. This improves memory efficiency and application performance."