0
0
JavaConceptBeginner · 3 min read

What is String Pool in Java: Explanation and Example

The string pool in Java is a special memory area where Java stores unique string literals to save memory. When you create a string literal, Java checks the pool first and reuses the existing string if it is already there, avoiding duplicate objects.
⚙️

How It Works

Imagine you have a box where you keep all your favorite stickers. Instead of buying the same sticker twice, you just reuse the one you already have. The Java string pool works similarly. It keeps one copy of each unique string literal in a special memory area.

When you write a string like "hello" in your code, Java checks the pool to see if it already has that string. If yes, it gives you the existing one instead of making a new copy. This saves memory and speeds up your program.

This only happens for string literals and strings created with the intern() method. Strings created with new String() are not automatically pooled.

💻

Example

This example shows how two string literals share the same object in the string pool, but strings created with new do not.

java
public class StringPoolExample {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = new String("hello");

        System.out.println(a == b); // true, same object from pool
        System.out.println(a == c); // false, different objects

        String d = c.intern();
        System.out.println(a == d); // true, intern() returns pooled string
    }
}
Output
true false true
🎯

When to Use

Use the string pool to save memory when you have many repeated string values, like keys, labels, or fixed messages. String literals are automatically pooled, so prefer using them over new String() when possible.

If you get strings dynamically but want to reuse existing ones, call intern() to add them to the pool.

This is helpful in large applications or when working with many strings to improve performance and reduce memory use.

Key Points

  • The string pool stores unique string literals to save memory.
  • String literals are automatically added to the pool.
  • new String() creates a new object outside the pool.
  • Use intern() to add strings to the pool manually.
  • Helps improve performance and reduce memory usage.

Key Takeaways

The string pool stores one copy of each unique string literal to save memory.
String literals automatically use the pool, but strings created with new do not.
Use intern() to add dynamically created strings to the pool.
Using the string pool improves performance and reduces memory use.
Prefer string literals over new String() when possible.