String intern() and the String Pool

The JVM keeps a table of unique strings called the string pool. Every string literal comes from it, and intern() adds other strings to it. This page explains how the pool works, shows exactly when two strings are the same object, measures the memory interning saves and the time it costs, and covers the alternatives that are usually better.

Contents

What the string pool is

A Java String is an object on the heap. Two strings can hold the same text and still be two separate objects, so ==, which compares object identity, can be false while equals, which compares the characters, is true.

The string pool is a hash table inside the JVM, called the StringTable in HotSpot, that maps text to one canonical String object. It is filled in two ways:

  • When a class first uses a string literal, the JVM resolves it through the pool, so every "hello" in every class of the program refers to the same object. Text blocks and compile-time constant expressions are literals too.
  • s.intern() looks up the text of s. If an equal string is already pooled it returns that one; otherwise it adds s and returns s.

Strings created at run time, by new String, concatenation with variables, StringBuilder, substring, reading a file or parsing JSON, are never pooled unless you intern them.

Where a string comes from, and whether it is pooled
SourcePooled?Example
String literal or text blockYes, always"hello"
Constant expression (JLS 15.29)Yes, folded by the compiler"data" + "base", "v" + 21
intern()Yes, returns the pooled copyinput.intern()
new String(...)No, always a new objectnew String("hello")
Run-time concatenation, StringBuilderNoprefix + id
I/O, parsing, substring, splitNoreader.readLine()

Since Java 7 the pooled strings live in the ordinary heap, not in the old fixed-size PermGen area, so the pool can grow and unused entries can be garbage collected. Every example on this page ran on JDK 21.

When two strings are the same object

The program creates the text hello in seven different ways and compares each with a literal using ==. Comparing with == is exactly what you should not do in normal code, but here it is the tool for seeing identity.

Java
public class InternBasics {

    public static void main(String[] args) {
        String a = "hello";                         // literal: from the string pool
        String b = "hello";                         // same literal: same pooled object
        String c = new String("hello");             // always a new object on the heap
        String d = c.intern();                      // the pooled object with equal content
        String block = """
            hello""";                               // a text block is a literal too

        System.out.println("a == b            " + (a == b));
        System.out.println("a == c            " + (a == c));
        System.out.println("a.equals(c)       " + a.equals(c));
        System.out.println("a == c.intern()   " + (a == d));
        System.out.println("c == c.intern()   " + (c == d));
        System.out.println("a == text block   " + (a == block));
        System.out.println("a == Other.GREETING " + (a == Other.GREETING));

        // Strings built at run time are new objects, even with the same content
        String built = new StringBuilder("hel").append("lo").toString();
        String fromChars = String.valueOf(new char[] {'h', 'e', 'l', 'l', 'o'});
        System.out.println("a == built        " + (a == built));
        System.out.println("a == fromChars    " + (a == fromChars));
        System.out.println("a == built.intern() " + (a == built.intern()));
    }
}

class Other {
    static final String GREETING = "hello";        // literals are shared across classes
}

Output:

Output
a == b            true
a == c            false
a.equals(c)       true
a == c.intern()   true
c == c.intern()   false
a == text block   true
a == Other.GREETING true
a == built        false
a == fromChars    false
a == built.intern() true
  • The two literals are the same object, and so are the text block and the constant Other.GREETING in another class. The pool is shared by the whole JVM.
  • new String("hello") is a different object even though equals is true. c.intern() returns the pooled literal, which is why a == c.intern() is true and c == c.intern() is false: c itself was not added, because an equal string was already there.
  • Strings built with StringBuilder or from a char[] are new objects. Interning one of them returns the literal.

Constant expressions: what the compiler folds

The compiler evaluates some expressions itself and stores only the result in the class file. Whether an expression qualifies depends on small details, such as whether a variable is final and how it was initialized, so the program tests the cases that are easy to confuse.

Java
public class ConstantFolding {

    static final String DATA = "data";                 // constant variable
    static final String LATE = String.valueOf("data"); // final, but not a constant
    static String notFinal = "data";

    public static void main(String[] args) {
        String db = "database";

        final String data = "data";                // final local with a literal: constant
        String base = "base";                      // ordinary variable
        final String computed = data.substring(0); // final, but computed at run time

        show("\"data\" + \"base\"", "data" + "base" == db);
        show("data + \"base\" (final)", data + "base" == db);
        show("DATA + \"base\" (static)", DATA + "base" == db);
        show("\"data\" + base", "data" + base == db);
        show("LATE + \"base\"", LATE + "base" == db);
        show("notFinal + \"base\"", notFinal + "base" == db);
        show("computed + \"base\"", computed + "base" == db);
        show("(\"data\" + base).intern()", ("data" + base).intern() == db);

        // Other constant expressions fold too
        show("\"v\" + 21", "v" + 21 == "v21");
        show("true ? \"a\" : \"b\"", (true ? "a" : "b") == "a");
        show("\"x\" + 'y'", "x" + 'y' == "xy");
    }

    static void show(String label, boolean sameObject) {
        System.out.printf("%-26s %b%n", label, sameObject);
    }
}

Output:

Output
"data" + "base"            true
data + "base" (final)      true
DATA + "base" (static)     true
"data" + base              false
LATE + "base"              false
notFinal + "base"          false
computed + "base"          false
("data" + base).intern()   true
"v" + 21                   true
true ? "a" : "b"           true
"x" + 'y'                  true
  • Two literals joined with + are folded into the literal "database", so the result is the pooled object.
  • A final variable initialized with a constant expression is a constant variable, local or static, and folds the same way: data + "base" and DATA + "base" are both true.
  • LATE is static final but is initialized with a method call, and computed is final but calls substring. Neither is a constant, so both concatenations happen at run time and create new objects. A non-final variable never folds.
  • Numbers, characters and conditional expressions with constant operands also fold: "v" + 21 is the same object as "v21".

This is why code that compares with == can pass a test full of literals and fail in production.

The pool lives in the heap and is garbage collected

A common worry is that interning fills a permanent area until the JVM crashes. The program checks the table size, then interns a string built at run time, drops all references to it and asks for garbage collection, with a WeakReference to see whether it was collected.

Java
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import com.sun.management.HotSpotDiagnosticMXBean;

public class PoolInHeap {

    public static void main(String[] args) {
        HotSpotDiagnosticMXBean vm = ManagementFactory.getPlatformMXBean(
            HotSpotDiagnosticMXBean.class);
        System.out.println("StringTableSize = " + vm.getVMOption("StringTableSize").getValue());

        // An interned string that nothing else refers to can be garbage collected
        WeakReference<String> ref = new WeakReference<>(makeInterned(4711));
        System.out.println("before GC, still in pool? " + (ref.get() != null));
        for (int i = 0; i < 5 && ref.get() != null; i++) {
            System.gc();
        }
        System.out.println("after GC, collected?      " + (ref.get() == null));

        // A literal is held by the class's constant pool, so it stays
        WeakReference<String> literal = new WeakReference<>("a literal in this class");
        System.gc();
        System.out.println("literal collected?        " + (literal.get() == null));

        // intern() of an equal string after collection returns a fresh pooled object
        String again = makeInterned(4711);
        System.out.println("re-interned: " + again + ", same as a new intern() call? "
            + (again == makeInterned(4711)));
    }

    // Built at run time from a parameter, so it is not a literal of this class
    static String makeInterned(int id) {
        return ("session-" + id).intern();
    }
}

Output:

Output
StringTableSize = 65536
before GC, still in pool? true
after GC, collected?      true
literal collected?        false
re-interned: session-4711, same as a new intern() call? true
  • StringTableSize is the number of buckets in the hash table, 65536 by default on JDK 21. HotSpot resizes the table as it fills, so the option rarely needs changing; -XX:+PrintStringTableStatistics prints how full it is when the JVM exits.
  • The interned session-4711 was collected once nothing referred to it. The pool holds its entries weakly, so interning many short-lived values does not leak memory.
  • The literal was not collected, because the class that uses it keeps it alive for as long as the class is loaded.
  • After collection, interning equal text again simply pools a new object, and later calls return that one.

The string built in makeInterned uses a parameter on purpose. Written as "session-" + 4711 it would be a constant expression, a literal of the class, and would never be collected.

What interning saves: duplicate values

Interning pays off when a program holds many strings with few distinct values, like a country code column loaded from a file. The program keeps a million such strings twice, once as separate objects and once interned.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;
import java.util.List;

public class InternMemory {

    static long usedMb() {
        Runtime rt = Runtime.getRuntime();
        System.gc();
        return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
    }

    public static void main(String[] args) {
        // 1,000,000 strings that contain only 4 distinct values, like a "country" column
        String[] codes = {"IN", "US", "DE", "BR"};

        long before = usedMb();
        List<String> plain = new ArrayList<>();
        for (int i = 0; i < 1_000_000; i++) {
            plain.add(new String(codes[i % 4]));     // a fresh object each time
        }
        long plainMb = usedMb() - before;

        List<String> interned = new ArrayList<>();
        for (int i = 0; i < 1_000_000; i++) {
            interned.add(new String(codes[i % 4]).intern());   // collapses to 4 objects
        }
        long internedMb = usedMb() - before - plainMb;

        Set<String> objects = Collections.newSetFromMap(new IdentityHashMap<>());
        objects.addAll(interned);                    // counts objects, not values
        long distinctInterned = objects.size();
        System.out.println("distinct objects, interned list: " + distinctInterned);
        System.out.println("approx. memory, plain list:    " + plainMb + " MB");
        System.out.println("approx. memory, interned list: " + internedMb + " MB");
        System.out.println(plain.size() + interned.size() + " strings kept alive");
    }
}

Output (memory figures are approximate and vary with the JVM and its settings):

Output
distinct objects, interned list: 4
approx. memory, plain list:    28 MB
approx. memory, interned list: 5 MB
2000000 strings kept alive
  • The interned list holds a million references to just 4 string objects. An IdentityHashMap-based set counts objects rather than values, which is why it reports 4.
  • The plain list used about 28 MB and the interned list about 5 MB. The remaining 5 MB is the list's own array of references, which both lists need.
  • Each separate two-letter string costs an object header, a hash field, a length and its own byte array: more than 20 bytes for 2 bytes of text. Short duplicated strings are where the overhead is largest.

What interning costs, and the alternatives

intern() is a native call into a shared hash table, which costs more than a lookup in a Java map. The program compares it with a HashMap and a ConcurrentHashMap used as hand-made pools, on values with 10 distinct strings and on a million unique ones. The program reports the fastest of three runs for each pool.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.UnaryOperator;

public class InternCost {

    public static void main(String[] args) {
        int n = 1_000_000;
        String[] fewDistinct = new String[n];
        String[] allUnique = new String[n];
        for (int i = 0; i < n; i++) {
            fewDistinct[i] = new String("status-" + (i % 10));
            allUnique[i] = new String("order-" + i);
        }

        System.out.println("1,000,000 strings with 10 distinct values:");
        time("String.intern()", fewDistinct, String::intern);
        Map<String, String> map = new HashMap<>();
        time("HashMap pool", fewDistinct, s -> map.computeIfAbsent(s, k -> k));
        Map<String, String> concurrent = new ConcurrentHashMap<>();
        time("ConcurrentHashMap pool", fewDistinct, s -> concurrent.computeIfAbsent(s, k -> k));

        System.out.println("1,000,000 unique strings:");
        time("String.intern()", allUnique, String::intern);
        Map<String, String> map2 = new HashMap<>();
        time("HashMap pool", allUnique, s -> map2.computeIfAbsent(s, k -> k));
    }

    // Best of 3 runs; later runs find every value already pooled
    static void time(String name, String[] values, UnaryOperator<String> pool) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            for (String v : values) {
                pool.apply(v);
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-24s %6.1f ms%n", name, best / 1e6);
    }
}

Output (rough comparison on a 2-CPU Linux machine, JDK 21; times vary between runs):

Output
1,000,000 strings with 10 distinct values:
  String.intern()            66.3 ms
  HashMap pool               14.0 ms
  ConcurrentHashMap pool     10.7 ms
1,000,000 unique strings:
  String.intern()           420.3 ms
  HashMap pool               18.3 ms
  • With 10 distinct values, both map-based pools were several times faster than intern(). The map lookup is ordinary Java code that the JIT compiles inline.
  • With a million unique values, intern() was more than ten times slower than the HashMap, because every call adds a new entry to the native table. Interning mostly unique values, such as order IDs or free text, costs time and saves nothing.
  • A map you own can also be cleared, sized and scoped to one data set, and a ConcurrentHashMap is safe to share between threads.

The JVM can also save the memory without changing identity. With -XX:+UseStringDeduplication, the garbage collector finds strings with equal content and makes them share one character array. It was added for G1 in JDK 8u20 (JEP 192), and Java 18 added it to the Serial, Parallel and Z collectors. It is off by default, needs no code changes, and only processes strings that have survived a few collections (StringDeduplicationAgeThreshold, 3 by default).

Identity traps

The real danger of the pool is that it makes == appear to work. The program checks a role with ==, first with a literal and then with the same text from a Scanner and from split, as it would arrive in a real application.

Java
import java.util.Scanner;

public class IdentityTraps {

    public static void main(String[] args) {
        // Works with literals, so it passes a quick test...
        System.out.println("isAdmin(\"admin\") with a literal: " + isAdmin("admin"));

        // ...but fails with the same text read at run time
        Scanner in = new Scanner("admin guest");
        String typed = in.next();
        System.out.println("typed = \"" + typed + "\", isAdmin: " + isAdmin(typed)
            + ", equals: " + "admin".equals(typed));
        String fromSplit = "user=admin".split("=")[1];
        System.out.println("from split, isAdmin: " + isAdmin(fromSplit));

        // Literals are shared JVM-wide, so locking on one shares the lock with any other code
        System.out.println("Library.LOCK == \"lock\": " + (Library.LOCK == "lock"));
    }

    static boolean isAdmin(String role) {
        return role == "admin";                    // compares identity: a bug
    }
}

class Library {
    static final String LOCK = "lock";             // synchronized (LOCK) would be shared
}

Output:

Output
isAdmin("admin") with a literal: true
typed = "admin", isAdmin: false, equals: true
from split, isAdmin: false
Library.LOCK == "lock": true
  • isAdmin("admin") is true because both sides are the pooled literal. The typed and the split value are new objects, so the same check returns false, while equals returns true.
  • Do not "fix" this by interning the input so that == works. It is slower than equals and breaks as soon as one caller forgets. Compare text with equals, as described on the string comparison page.
  • Because literals are shared JVM-wide, Library.LOCK is the same object as any other "lock" literal. Code that does synchronized (LOCK) then shares its lock with unrelated code that happens to use the same literal. Lock on a private new Object() instead.

When to intern

Choosing how to handle duplicate strings
SituationDo this
Comparing two stringsa.equals(b), never ==
Many long-lived strings, few distinct valuesA HashMap or ConcurrentHashMap pool, or intern()
Mostly unique valuesDo not intern
Memory full of duplicate strings, no code changes possible-XX:+UseStringDeduplication
Values from a small fixed setAn enum, which is smaller and type-safe
A lock objectprivate final Object lock = new Object(), not a string

To find duplicate strings in a real application, take a heap dump and look at the duplicate strings report of a heap analyzer. For more on string memory and speed, see string performance.