🔤 Strings & Text · Beginner

StringBuilder in Java

Mutable builder: append, insert, reverse, deleteCharAt; why it beats + in loops.

🧩 The mysteryA loop builds a report with report += line;. With 1,000 lines it's instant. With 100,000 lines, you have time to make coffee. Same code — why does it collapse?

The hidden copying

Strings are immutable, so report += line can't append in place. It builds a new String containing all the old text plus the line. Line 50,000 copies 49,999 lines first. The total work grows quadratically — double the lines, four times the time.

A whiteboard instead of stone

StringBuilder is a mutable sequence of characters: one buffer that grows as you append. No copying of everything each time. When you're done, toString() gives you the final String.

var sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
    sb.append(i).append(',');
}
String result = sb.toString(); // "0,1,2,"

Chaining and editing

Most methods change the builder itself and return it (this), so calls can be chained. Besides append, you can insert(index, x), deleteCharAt(index) and reverse() — all on the same object.

var sb = new StringBuilder("hello");
sb.deleteCharAt(0);  // "ello"
sb.insert(0, "J");   // "Jello"
🔮 Predict it

Order of operations

What does this print?

var sb = new StringBuilder("dog");
sb.insert(0, "hot ").append("s");
System.out.println(sb);
  1. hot dog
  2. hot dogs
  3. dogs hot
  4. dogshot
Show the answer

hot dogs. insert(0, ...) puts "hot " at the front, then append adds "s" at the end — both on the same builder, which println prints via toString().

🔮 Predict it

A sweet reversal

What does this print?

var sb = new StringBuilder("stressed");
sb.reverse();
System.out.println(sb);
  1. stressed
  2. desserts
  3. dessert
Show the answer

desserts 🍰 — reverse() flips the builder in place. No need to assign the result: the builder itself changed.

⚠️ The trap

equals doesn't compare text

StringBuilder does not override equals: it inherits Object's version, which compares references. Two builders holding "x" are not "equal". Compare their contents with compareTo (StringBuilder is Comparable since Java 11) or a.toString().equals(b.toString()).

var a = new StringBuilder("x");
var b = new StringBuilder("x");
a.equals(b);          // false!
int c = a.compareTo(b); // 0
💼 In the real world

In real projects

Building CSV exports, log lines, SQL or HTML in loops? Use a StringBuilder. For a single expression like a + ":" + b, don't bother — since Java 9 the compiler already optimizes that (JEP 280). The danger zone is += inside a loop.

Key takeaways

  1. StringBuilder methods modify the same object
  2. Most methods return this, so you can chain them
  3. Call toString() to get the final String
  4. StringBuilder does not override equals: compare with toString() or compareTo
🤯 Did you know?

new StringBuilder() starts with room for 16 characters. When it fills up, it grows to about double (old × 2 + 2), so even millions of appends stay cheap on average.

Practice questions

What does this print?

var sb = new StringBuilder("cat");
sb.append("s").insert(0, "my ");
System.out.println(sb);
  1. cats
  2. my cats
  3. my cat
  4. catsmy
Check your answer

my cats. append adds "s" at the end, then insert(0, ...) puts "my " at index 0. Both modify the same builder, which println prints via toString.

What does this print?

var sb = new StringBuilder("hello");
sb.deleteCharAt(0).reverse();
System.out.println(sb);
  1. olleh
  2. olle
  3. ello
  4. lleh
Check your answer

olle. deleteCharAt(0) removes 'h' giving "ello", and reverse turns it into "olle". The chained calls act on the same object.

Next: StringBuilder has an older twin, StringBuffer. Why does nobody invite it anymore?