Bird
Raised Fist0
JavaHow-ToBeginner · 3 min read

String Pool in Java: How It Works and Why It Matters

The String pool in Java is a special memory area where string literals are stored to save memory by reusing identical strings. When you create a string literal, Java checks the pool first and returns the existing string if found, avoiding duplicate objects. This helps improve performance and memory efficiency.
📐

Syntax

The String pool works automatically with string literals and the intern() method.

  • String s = "hello"; creates or reuses a string in the pool.
  • String s2 = new String("hello"); creates a new object outside the pool.
  • s2 = s2.intern(); adds the string to the pool or returns the existing one.
java
String s1 = "hello";
String s2 = new String("hello");
String s3 = s2.intern();
💻

Example

This example shows how string literals share the same object in the pool, while strings created with new do not, unless intern() is used.

java
public class StringPoolExample {
    public static void main(String[] args) {
        String s1 = "java";
        String s2 = "java";
        String s3 = new String("java");
        String s4 = s3.intern();

        System.out.println(s1 == s2); // true, same pool object
        System.out.println(s1 == s3); // false, different objects
        System.out.println(s1 == s4); // true, s4 refers to pool object
    }
}
Output
true false true
⚠️

Common Pitfalls

Many beginners expect == to compare string content, but it compares references (memory addresses). Strings created with new are not in the pool by default, so == returns false even if contents match. Always use equals() to compare string content.

Also, forgetting to use intern() when needed can cause unexpected memory use or comparison results.

java
String a = new String("test");
String b = "test";

// Wrong: compares references
System.out.println(a == b); // false

// Right: compares content
System.out.println(a.equals(b)); // true

// Using intern to get pool reference
String c = a.intern();
System.out.println(b == c); // true
Output
false true true
📊

Quick Reference

ConceptDescription
String literalStored in the String pool automatically
new String()Creates a new object outside the pool
intern()Adds string to pool or returns existing pool string
== operatorCompares references, not content
equals() methodCompares string content
✅

Key Takeaways

Java String pool stores string literals to save memory by reusing objects.
Use string literals or intern() to ensure strings are in the pool.
Never use == to compare string content; use equals() instead.
new String() creates a new object outside the pool unless intern() is called.
String pool improves performance and reduces memory usage.