The string pool & ==
Two strings that print the same can still be two different objects.
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
Static storage
interned literalsOne 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.
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.
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 }}