Skip to content
C

StringBuffer

StringBuffer works almost identically to StringBuilder — it's mutable and used for building or modifying text. The key difference is that StringBuffer is thread-safe, meaning it's designed to be used safely when multiple threads access it a…


1. What is StringBuffer?

StringBuffer works almost identically to StringBuilder — it's mutable and used for building or modifying text. The key difference is that StringBuffer is thread-safe, meaning it's designed to be used safely when multiple threads access it at the same time.

2. Why is it used?

In programs where multiple parts of the code (running as separate threads) might modify the same text data at the same time, StringBuffer protects against data corruption, unlike StringBuilder.

3. Real-Life Example

Think of a shared notice board in an office, where a security guard makes sure only one person edits it at a time so nothing gets messed up. StringBuffer behaves like this careful, one-at-a-time editing process.

4. Syntax

java
StringBuffer sb = new StringBuffer(); sb.append("text"); sb.insert(position, "text"); sb.reverse();

5. Example Program

java
public class StringBufferDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); } }

Output:

Hello World

6. Key Points to Remember

  • StringBuffer methods are synchronized (thread-safe); StringBuilder methods are not.
  • Because of this safety check, StringBuffer is slightly slower than StringBuilder in single-threaded programs.
  • Use StringBuilder for regular, single-threaded work, and StringBuffer only when multiple threads need safe access — this distinction is a common interview question.