Why is String immutable in Java, and how does the string constant pool work? What does new String("hi") do differently from "hi"?
Show the explanation
A String object never changes; methods like toUpperCase() or concat() return new strings. Reasons:
- Pooling — identical literals can share one object safely.
- Security and correctness — strings used as file names, class names or URLs cannot be changed after they are checked.
- Thread safety — immutable objects can be shared without locks.
- Hashing — the hash code can be cached, which makes strings fast
HashMapkeys.
String literals are interned in the string pool (part of the heap): every "hi" in the program refers to the same object. new String("hi") always creates a separate object.
String a = "hi", b = "hi", c = new String("hi");
System.out.println(a == b); // true - same pooled object
System.out.println(a == c); // false - c is a different object
System.out.println(a.equals(c)); // true - same characters
System.out.println(a == c.intern()); // true - intern() returns the pooled copyCompile-time constants are folded too: "h" + "i" == "hi" is true, but concatenation of a variable at runtime produces a new object.
Original UniCircle question. Last reviewed 22 Oct 2026.
