2. String Is Immutable
String objects are immutable in Java; every modification creates a new object. The string pool and intern() affect identity equality, making == vs .equals() a classic interview trap.
Explanation
String is immutable because its internal byte[] array is final and the class is final itself. Immutability makes strings safe to share across threads, safe to use as HashMap keys (hash never changes), and enables the string pool optimisation.
The string pool (also called the interned string pool) is a cache of String objects in the heap. String literals declared in source code are automatically interned โ all occurrences of "hello" in the same JVM share a single object. String.intern() lets you explicitly intern a runtime string.
The classic interview trap: == compares object identity (memory address), .equals() compares character content. Two string literals with the same content will be == (same pool entry), but strings created with new String(...) will not be, even if the characters are identical.
Example
public class StringImmutability {
public static void main(String[] args) {
// Literals: same pool entry
String a = "hello";
String b = "hello";
System.out.println(a == b); // true (same pool object)
System.out.println(a.equals(b)); // true (same content)
// new String bypasses the pool
String c = new String("hello");
System.out.println(a == c); // false (different object)
System.out.println(a.equals(c)); // true (same content)
// intern() puts it back in the pool
String d = c.intern();
System.out.println(a == d); // true (now same pool object)
// Immutability: concat creates a NEW object
String original = "Java";
String modified = original.concat(" 21");
System.out.println(original); // "Java" โ unchanged
System.out.println(modified); // "Java 21" โ new object
}
}Sources
- https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html โ String API docs
- https://openjdk.org/jeps/254 โ JEP 254: Compact Strings (internal representation change in Java 9)