Creating StringBuffer Objects
1. Why StringBuffer? (beginner)
StringBuffer = mutable (editable!) String — same object grows, no garbage! Plus thread-safe (synchronized — many threads safe). Use when text changes a lot (loops, editors).
2. Four Ways to Create (exam list!)
StringBuffer sb1 = new StringBuffer(); // empty, capacity 16
StringBuffer sb2 = new StringBuffer("hello"); // from String → "hello"
StringBuffer sb3 = new StringBuffer(100); // empty, capacity 100 (big file!)
StringBuffer sb4 = new StringBuffer(sb2); // copy of another!
System.out.println(sb2 + " cap=" + sb2.capacity()); // hello cap=21 (16+5!)
Capacity = room reserved (auto-grows: newCap = old*2+2 when full!). Length = used chars.
3. Mutability Proof (vs String!)
String s = "hi";
s.concat("!"); // new object thrown away — s still "hi"!
System.out.println(s); // hi
StringBuffer sb = new StringBuffer("hi");
System.out.println(System.identityHashCode(sb)); // e.g. 111
sb.append("!"); // SAME object edited!
System.out.println(System.identityHashCode(sb)); // 111 (SAME! — proof!)
System.out.println(sb); // hi! (changed in place!)
4. Traps
- No literals:
StringBuffer sb = "hi";ERROR (mustnew!). ==compares addresses (like all objects) — use.toString().equals()for content.- Default capacity 16 surprises in
capacity()questions!
5. Exam Points
- 4 constructors + capacity rule — 5 marks, frequent.
- Mutability proof (same hashCode) vs String — 5 marks, very frequent.