• ↑↓ to navigate
  • ↵ to open
  • ⟶ to select
  • ⌘ ⌥ ↵ to open in a panel
  • ←→ to navigate
  • esc to dismiss
⌘ '
keyboard shortcuts

What’s Being Compared

Java provides three classes for working with character sequences: immutable String, thread-safe mutable StringBuffer, and non-thread-safe mutable StringBuilder. Understanding when to use each is critical for writing correct and performant code.

The Core Tension

The tradeoff is between safety and performance. Immutability (String) is the safest but creates garbage under modification. Synchronization (StringBuffer) adds thread safety but incurs overhead. StringBuilder drops synchronization for speed but is unsafe in shared contexts.

Comparison

DimensionStringStringBufferStringBuilder
MutabilityImmutableMutableMutable
Thread safetySafe (immutable)Safe (synchronized)Unsafe
PerformanceSlow for modificationModerate (sync overhead)Fastest
Use caseFixed text, constants, keysLegacy code (Java 1.0)Dynamic building (Java 1.5+)
Concatenation in loopsO(n²) garbageO(n) bufferO(n) buffer

When to Use String

  • The value never changes after creation
  • As map keys (immutability guarantees hash stability)
  • Thread-safe sharing without synchronization
  • Short, fixed strings

When to Use StringBuilder

  • Building strings dynamically in a single-threaded context
  • Inside methods (local variable, no sharing)
  • String concatenation in loops (compiler translates + to StringBuilder anyway)

When to Use StringBuffer

  • Mutable string building in a shared, multi-threaded context
  • Legacy code that already uses it
  • Rare — StringBuilder is almost always preferred in modern code

The Insight

The Java compiler itself prefers StringBuilder — "a" + "b" + "c" is compiled to new StringBuilder().append("a").append("b").append("c").toString(). There is almost never a reason to use StringBuffer in new code. The real choice is between String (immutable, safe) and StringBuilder (mutable, fast).

Visual Explanation

java_string_types_compared A Java String Types Co Input B Java String Types Co Core Mechanism A->B triggers C Java String Types Co Output B->C produces

Semantic Network

semantic_java_string_types_compared THIS Java String Types Co REL1 Related Concept THIS--REL1 related REL2 Builds Into THIS--REL2 builds into

Connections