String pool

The String pool is a special region inside the JVM heap where String literals are interned β€” deduplicated so identical literals share a single object. This makes == coincidentally work for literals, but you must still use .equals() for string comparison in general.

Interning in action

String a = "hello";
String b = "hello";
System.out.println(a == b); // true β€” both reference the pooled literal

String c = new String("hello");
System.out.println(a == c); // false β€” new String bypasses the pool
System.out.println(a.equals(c)); // true β€” content equality

Explicit interning

String x = new String("world");
String y = x.intern();         // returns the pooled copy
System.out.println("world" == y); // true

Why it exists

Strings are among the most-allocated objects in any Java application. Interning repeated literals saves heap memory and speeds up equality checks for the JVM's internal use (class names, method names).

Should you rely on it?

No. Always compare strings with .equals(). The pool is a JVM-internal optimisation β€” don't let your program's correctness depend on it.