Skip to content
Codescope

The string pool & ==

Two strings that print the same can still be two different objects.

intro8 min7 steps

Before you start

In Java, strings are objects. That means every string has an address on the heap, and two strings that print the same could be two *different* objects at two different addresses.

For efficiency, Java keeps a special **string pool** for string literals. Two literals with the same text share one object — but a string built at runtime (with new String(...) or by concatenation) gets its own separate object.

This lesson shows exactly which strings live in the pool and which don't, and why comparing strings with == is a bug — you almost always want .equals().

Stack

main()
aString
0x5a00

Static storage

interned literals
string pool @0x5a00one entry per distinct literal, for the life of the JVM
value
"hello"

One object in the pool. a refers to it.

Step 1 of 7. A literal comes from the pool. `String a = "hello"` does not allocate a new object each time. The JVM keeps a pool of distinct string literals, and `a` gets a reference to the pooled one. This is safe only because strings are immutable — sharing one object between unrelated pieces of code would be reckless otherwise.

01 / 07

Step 01 / 07

A literal comes from the pool

String a = "hello" does not allocate a new object each time. The JVM keeps a pool of distinct string literals, and a gets a reference to the pooled one.

This is safe only because strings are immutable — sharing one object between unrelated pieces of code would be reckless otherwise.

string-pool.javaJava
public class Main {    public static void main(String[] args) {        String a = "hello";              // from the pool        String b = "hello";              // same pooled object        String c = new String("hello");  // forced new object        System.out.println(a == b);      // true  — same reference        System.out.println(a == c);      // false — different objects        System.out.println(a.equals(c)); // true  — same characters        String d = c.intern();           // back to the pooled one        String s = "he" + "llo";         // folded at compile time    }}