String Pool

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • The String Pool is a special storage area in the Java Heap memory.
  • When you create a String using a literal ("abc"), the JVM checks the pool. If "abc" already exists, it returns a reference to the pooled instance. If not, it adds it to the pool.
  • This saves significant memory since Strings are the most heavily used objects in Java.

Concept

Because Strings are immutable, it is perfectly safe for multiple variables to point to the exact same String object in memory. Java exploits this to save space.

If you create a String using the new keyword (e.g., new String("abc")), Java bypasses the String Pool optimization and forces the creation of a brand new object in the standard Heap space.

intern() Method

You can manually move a dynamically created String into the String Pool by calling .intern() on it.

Examples

public class StringPoolExample {
    public static void main(String[] args) {
        String s1 = "Hello"; // Created in String Pool
        String s2 = "Hello"; // Points to the EXISTING object in the String Pool
        
        System.out.println(s1 == s2); // true (same memory address)
        
        String s3 = new String("Hello"); // Created in the regular Heap, outside the pool
        
        System.out.println(s1 == s3); // false (different memory addresses)
        
        String s4 = s3.intern(); // Moves/finds "Hello" in the pool
        
        System.out.println(s1 == s4); // true (s4 now points to the pool instance)
    }
}

Interview Questions

Q: What is the difference between String s = "Test" and String s = new String("Test")?
A: String s = "Test" uses the String Pool. If "Test" already exists, no new object is created.
String s = new String("Test") guarantees a new object is created in the heap, regardless of whether "Test" exists in the pool. It actually creates two objects if "Test" wasn’t already in the pool (one in the pool for the literal, and one in the heap for the new keyword).

Q: Why shouldn’t you use == to compare Strings?
A: The == operator checks for reference equality (do they point to the exact same memory address). Because Strings can be created outside the pool using new or via concatenation at runtime, two strings might have the exact same text but different memory addresses. You should always use .equals() to check for value equality (do they contain the same characters).