Part 13 / Topic 3 of 8
== vs. .equals(), and the String pool
== on objects compares identity — are these two variables pointing at the exact same object in memory? .equals() (when a class overrides it sensibly, as String does) compares value — do they represent the same data? For String, these can disagree in ways that surprise people who learned == on ints first.
The string pool is a cache of String literals the JVM keeps so that identical literal text doesn't get a new object every time it appears in the source.
Think of the pool as a library's single copy of a popular book: every reader asking for "Pune" by name gets handed the same physical copy; asking a photocopier (new String(...)) for one instead always hands back a fresh, separate copy with identical words on the page.
String city1 = "Pune";
String city2 = "Pune";
System.out.println(city1 == city2); // true: same pooled object
String city3 = new String("Pune");
System.out.println(city1 == city3); // false: a deliberately fresh object
System.out.println(city1.equals(city3)); // true: same value
$ javac StringPoolAndInterning.java
$ java StringPoolAndInterning
== 1. Two literals with the same text share one object ==
city1 == city2: true
city1.equals(city2): true
== 2. new String(...) always makes a fresh object, even with the same text ==
city1 == city3: false
city1.equals(city3): true
== 3. intern() puts (or finds) the text in the pool, and returns THAT reference ==
city1 == city4: true
== 4. A String built at runtime (not a compile-time constant) is NOT auto-pooled ==
city1 == built: false
city1 == foldedAtCompileTime: true
== 5. Immutability means every 'change' makes a new object ==
identity changed: true (same variable name, different object)
(identityHashCode values themselves are not meaningful, only whether they differ)
.intern() looks the string's text up in the pool (adding it if it isn't already there) and returns that shared reference — which is why city3.intern() == city1 is true even though city3 itself never was. A string built at runtime ("Pu" + prefixVariable) is not automatically pooled — javac can only pool text it can prove is a compile-time constant, so "Pu" + "ne" (both literals) folds to "Pune" itself at compile time, but prefix + "ne" (one variable) genuinely allocates a new object when the program runs. And because String is immutable, order = order + "-1001" never modifies the original — it allocates an entirely new String and points order at that instead, which System.identityHashCode changing confirms.
⚠️ Never compare two
Strings (or any boxed type) with==for value equality. It happens to work for pooled literals and small cached numbers (section 4), which is exactly what makes the bug hide until someone passes in a value built at runtime.
Full program: examples/StringPoolAndInterning.java.
Done here? The practice set for Part 13 — including the solutions — is on the part page.