StringBuffer vs StringBuilder in Java — Java Technical Interview Questions & Answers
StringBuffer vs StringBuilder in Java
StringBuffer vs StringBuilder in Java
- Both are mutable text builders. StringBuffer methods are synchronized — thread-safe, slower. StringBuilder is not synchronized — faster, one thread.
- Student programs almost always want StringBuilder. Pick StringBuffer only if two threads share the same buffer.
- String itself is immutable. Don’t confuse all three.
- Let's take this on the board with one tiny Main class — no extra files. StringBuffer vs StringBuilder in Java — output: Hi Java. append changes the same StringBuilder — not a new String each time. Start from main, go line by line, and stop at each print. That output is the proof for StringBuffer vs StringBuilder.
Technical Interview Tip: Builder for one thread. Buffer if shared. String cannot change.
Code Examples for StringBuffer vs StringBuilder in Java
Example
// StringBuilder demo
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hi");
sb.append(" Java");
System.out.println(sb.toString());
}
}StringBuffer vs StringBuilder in Java — output: Hi Java. append changes the same StringBuilder — not a new String each time.
How to Explain StringBuffer vs StringBuilder in Java to an Interviewer
Which is faster?
StringBuilder
Which is thread-safe?
StringBuffer