Strings and StringBuilder

Lesson 4 of 20

Append a StringBuilder to watch its buffer grow, then see why Strings refuse to change and copies pile up.

The big picture

Immutable vs builder

A Java String is carved in stone — every edit builds a new object. StringBuilder is the chisel: one mutable buffer you can grow, reverse and rewrite.

Immutable Strings

"cat".toUpperCase() does nothing on its own — the new string is discarded unless you assign it. s = s + "!" creates a fresh object.

Reads are cheap

s.charAt(i), s.length() and s.indexOf(x) are O(1) or a quick scan — reading never mutates anything.

The concat trap

s.concat(t) returns a new string. Ignore the return value and your change evaporates — the classic bug.

StringBuilder

A resizable char buffer. append() writes into spare capacity — amortized O(1) — and reverse() flips it in place.

Equality rules

s1 == s2 compares references; s1.equals(s2) compares characters. Use .equals for text, always.