Arrays and Strings · Introduction to Java Programming

StringBuilder Class

Watch lectures

StringBuilder Class

1. StringBuilder vs StringBuffer (beginner — one difference!)

Same API, same mutable magic — only difference: threads! StringBuffer = synchronized (thread-safe, slower). StringBuilder = NOT synchronized (faster, single-thread default!). Beginners: default to StringBuilder (loops, single thread).

2. Code — Drop-In Replacement (10× faster loop!)

// SLOW (String garbage!): 10,000 new objects!
String s = "";
for (int i = 0; i < 10000; i++) s += i; // O(n²) — exam's slow example!

// FAST (one object!): same result, ~100× faster!
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) sb.append(i);
String fast = sb.toString(); // convert once at end!
// StringBuffer version identical: new StringBuffer() + append (slower, safe threads)

3. Comparison Table (exam favourite!)

String StringBuffer StringBuilder
Mutable? No (new each edit!) Yes (same object) Yes (same object)
Threads? Safe (immutable!) Safe (synchronized) NOT safe (fast!)
Speed (loop) Slowest Fast Fastest
Use fixed text shared multi-thread text single-thread building (default!)

4. Traps

  • StringBuilder methods identical to StringBuffer (append/insert/delete/reverse — next topic!).
  • Need String back? .toString() (both!).
  • Multi-thread shared builder? Use StringBuffer (or lock!).

5. Exam Points

  • Three-way table + loop program — 7 marks, very frequent.
  • When to use which — 3 marks, frequent.
Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.

← All Introduction to Java Programming modules