StringBuffer in Java
StringBuffer is a class in the java.lang package that represents a mutable sequence of characters. Unlike String, which creates a new object every time you...
Mutable String Building with StringBuffer
StringBuffer is a class in the java.lang package that represents a mutable sequence of characters. Unlike String, which creates a new object every time you modify it, a StringBuffer lets you change, insert, delete, or append characters to the same underlying buffer. This makes StringBuffer the right choice when a program needs to build or transform a string through many steps, particularly inside loops.
Thread Safety: The Key Distinguishing Feature Every public method in StringBuffer is synchronized, meaning only one thread can execute it at a time. This built-in locking makes StringBuffer safe to use from multiple threads simultaneously without additional synchronization code. The trade-off is that acquiring and releasing locks adds overhead, so StringBuffer is slower than StringBuilder in single-threaded code. Choose StringBuffer specifically when multiple threads share the same buffer object.
Core Methods append(value) adds text to the end of the buffer. insert(index, value) inserts text at a specific position. delete(start, end) removes a range of characters. replace(start, end, str) swaps a range with new text. reverse() flips the entire character sequence. toString() converts the buffer to a plain String when you are done building.
Capacity and Growth StringBuffer internally uses a char array. The default initial capacity is 16 characters. When the buffer fills up, Java automatically allocates a new array roughly twice the size and copies the existing content. If you know in advance how large the final string will be, you can pass a capacity to the constructor—new StringBuffer(256)—to avoid repeated resizing.
Code Example: StringBuffer sb = new StringBuffer("Hello"); sb.append(", World"); sb.insert(5, "!"); sb.delete(6, 12); System.out.println(sb.toString()); // Hello!, World (varies by position)
StringBuffer sb2 = new StringBuffer("abcde"); sb2.reverse(); System.out.println(sb2); // edcba
Interview Tip: Expect a question asking you to compare String, StringBuffer, and StringBuilder. The three-way answer is: String is immutable; StringBuffer is mutable and thread-safe; StringBuilder is mutable but not thread-safe and therefore faster. Use StringBuilder in single-threaded code and StringBuffer only when thread safety is genuinely required.