Why this matters
- String concatenation inside a loop is the most common accidental performance bug in Java, and it is invisible in the source.
- The
==versus.equals()question has a specific answer for strings because of the pool, and that answer is asked constantly. - Strings are the most allocated type in almost every Java application, so the small decisions here add up.
Immutability, and why
Internally a String wraps a private final byte array with no method that writes to it. The
immutability is a deliberate design choice with four payoffs.
- Safe to share. Many references to one string cannot interfere, so the pool is possible at all.
- Thread-safe with no locking. No state changes, so no synchronisation is ever needed.
- Reliable as a map key. The hash code cannot drift after insertion, and
Stringcaches it after first use. - Secure. A file path or connection string passed to a library cannot be altered behind your back after validation.
The string pool
String literals are interned: the JVM keeps one copy in a pool and hands out the same reference for identical literals.
Compile-time constant expressions are folded and pooled; anything computed at run time is not.
Since Java 7 the pool lives in the heap rather than PermGen, so unreferenced pooled strings can be garbage collected like anything else.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 7 sections
- Concatenation and the loop trap
- Indy string concatenation (Java 9+)
- Compact Strings (Java 9+)
- StringBuilder and StringBuffer
- Comparison
- Methods worth knowing
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.