Skip to main content
PreparationZone Logo
PrepZone

Strings, Builders and the Pool

Why String is immutable, what the pool actually stores, and when to reach for StringBuilder.

Pass checkpoint below

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.
Binary data
InputStream / OutputStreamImages, PDFs, audio
BufferedInputStreamReads in blocks
Text data
Reader / WriterHandles character encoding
BufferedReaderGives you readLine()
Pick the family by data type, then wrap a buffer around it. Buffering is what turns thousands of tiny system calls into a handful of big ones.

Immutability, and why

Java
Loading compiler…

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 String caches 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.

Java
Loading compiler…

Compile-time constant expressions are folded and pooled; anything computed at run time is not.

Java
Loading compiler…

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.