Theory
The catalog that made 6000 copies
Month-end: BookBridge assembles its full catalog report.
String report = "";
for each book: report = report + line;
Remember immutability: every + builds a brand-new String and abandons the old one. 6000 lines means roughly 6000 discarded objects, each copying everything before it. The garbage collector cleans up, but you made it mop a flooded room.
For heavy, repeated editing of one text, Java offers a different tool: a mutable one.
Theory
Printed page vs whiteboard
A String is a printed page: to change one word you print a whole new page.
A StringBuffer is a whiteboard: walk up and add, squeeze in, erase or rewrite, and it stays the SAME whiteboard. The board is also slightly bigger than what is written on it, spare room so small additions need no new board. That spare room is its capacity.
Theory
Constructors and the capacity rule
3 constructors, one rule to memorise:
new StringBuffer(): empty, capacity 16new StringBuffer(50): empty, capacity 50new StringBuffer("Let Us C"): capacity = 16 + length, here 16 + 8 = 24
Keep 2 words apart: length() counts characters actually stored; capacity() counts the room allocated. A buffer holding "Let Us C" has length 8, capacity 24. Exceed the capacity and the buffer grows itself automatically; you never overflow it.
Practical
Editing in place
public class CatalogLine {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Let Us C");
System.out.println(sb.length()); // 8
System.out.println(sb.capacity()); // 24 (16 + 8)
sb.append(" 2nd Ed"); // same object, now longer
sb.insert(0, "* "); // squeeze in at the front
System.out.println(sb); // * Let Us C 2nd Ed
sb.delete(0, 2); // remove indexes 0,1 (end exclusive)
sb.setCharAt(0, 'G'); // the "update" operation
System.out.println(sb); // Get Us C 2nd Ed
}
}
At a glance
String vs StringBuffer (the exam table)
| Aspect | String | StringBuffer |
|---|---|---|
| Mutability | Immutable: every edit makes a new object | Mutable: edits happen in place |
| Best for | Fixed text, comparisons, keys | Repeated building and editing |
| Editing cost | New object per change | One object, grows as needed |
| Thread safety | Safe by being unchangeable | Safe: its methods are synchronized |
Quiz
What does new StringBuffer("Book").capacity() return?
- 16
- 4
- 20
- 0
Show the answer
20
The String constructor allocates 16 spare slots PLUS the initial content's length: 16 + 4 = 20. Option A is the capacity of an EMPTY buffer from new StringBuffer(). Option B confuses capacity with length(), which would indeed be 4. Option D would mean no room at all, which no constructor produces. The 16-plus-length formula is asked almost every year in some form.
Think first
Trace the reverse
StringBuffer sb = new StringBuffer("Us C"); sb.reverse(); System.out.println(sb); Flip it character by character in your head, spaces included, before tapping.
Show the answer
C sU. The 4 characters U, s, space, C become C, space, s, U. Two things worth noticing: the space is a character like any other and moves too; and reverse() changed sb ITSELF, no assignment needed, because StringBuffer edits in place. The same call on a String does not exist at all: to reverse a String, the standard trick is new StringBuffer(s).reverse().toString(), a favourite 2-mark question.
Watch out
Two traps, one honest note
Trap 1: String s = "abc"; s.concat("d"); changes nothing, but sb.append("d") changes sb. Students carry the assign-it-back habit into StringBuffer or, worse, the no-assign habit back into String.
Trap 2: delete(0, 2) removes indexes 0 and 1 only: end-exclusive, same convention as substring.
Honest note: your syllabus lists an update() method; StringBuffer's real names for updating are setCharAt(index, ch) and replace(start, end, s). Write those in the exam.
Theory
Why the methods return the buffer
append and insert return the very buffer you called them on, so calls chain like plumbing: sb.append(" 2nd Ed").insert(0, "* ").reverse(). The catalog loop becomes: create ONE StringBuffer, append 6000 lines, call toString() once at the end. Same output as the String version, a fraction of the garbage. And file away "its methods are synchronized": when Unit 4 introduces threads, StringBuffer is the string tool already built for them.
Summary
Key takeaways
- StringBuffer is mutable: append, insert, delete, setCharAt, replace and reverse edit one object in place.
- Constructors: empty (capacity 16), sized, or from a String (capacity 16 + length).
- length() = characters stored; capacity() = room allocated; the buffer grows itself when needed.
- delete and replace are end-exclusive, matching substring.
- The syllabus's update = setCharAt / replace in real StringBuffer vocabulary.
- Use String for fixed text, StringBuffer for heavy building; reverse a String via new StringBuffer(s).reverse().toString().
- Memory hook: String is a printed page, StringBuffer is a whiteboard.