StringBuffer in Java — Java Technical Interview Questions & Answers

StringBuffer in Java

StringBuffer in Java

  • StringBuffer is a mutable text builder. append, insert, reverse change the same object. Methods are synchronized — safer if two threads share it, a bit slower.
  • In a single-thread student program, StringBuilder is usually the better pick. Use StringBuffer when the buffer is shared across threads.
  • Don’t build a long string with + in a loop. Use append.
  • Let's take this on the board with one tiny Main class — no extra files. StringBuffer in Java — same append idea as Builder, but synchronized. Start from main, go line by line, and stop at each print. That output is the proof for StringBuffer.

Technical Interview Tip: Mutable + synchronized. Prefer StringBuilder unless two threads share it.

Code Examples for StringBuffer in Java

Example

// StringBuffer demo
public class Main {
  public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("Hi");
    sb.append(" Java");
    System.out.println(sb);
  }
}

StringBuffer in Java — same append idea as Builder, but synchronized.

How to Explain StringBuffer in Java to an Interviewer

Is StringBuffer immutable?

No Mutable

Why synchronized?

Two threads can share it safely