Java · OOP, JVM and backend craft

What is the difference between StringBuilder and StringBuffer?

EasystringbuilderstringbuffermutabilityUpdated Oct 2026
Quiz this track

Short answer

StringBuilder is mutable and not synchronized. StringBuffer is mutable and synchronized, so it is slower; prefer StringBuilder unless the same buffer is genuinely shared across threads.

Both classes build strings without creating an intermediate String for every append. StringBuilder is the modern default. StringBuffer predates the collections framework and synchronizes its methods, which adds overhead that is unnecessary when the builder stays inside one method.

java
public static String join(List<String> parts) {
    StringBuilder builder = new StringBuilder();
    for (String part : parts) {
        builder.append(part).append(',');
    }
    return builder.toString();
}
The builder is local to the method, so synchronization would add no value.

How to choose

  • StringBuilder for local string assembly and almost all application code
  • StringBuffer only for legacy APIs that require it
  • Neither is needed for a fixed number of concatenations the compiler can fold
  • Consider String.join or a stream collector for simple joining

StringBuilder is not thread-safe. Sharing one instance across threads without external synchronization corrupts its internal state. If a shared builder is truly required, either synchronize access or use StringBuffer and accept the cost.

Do not use string concatenation with += inside a loop. It creates a new String and a new builder on each iteration in the common compiled form, which is much slower than one reusable builder.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is StringBuffer slower than StringBuilder?
  2. 2Is StringBuilder safe to share between threads?
  3. 3When is plain concatenation fine?
  4. 4How would you join a list of strings without a builder?

Say it in the interview

Both accumulate characters without creating a new String on every append. StringBuilder is unsynchronized and therefore faster, while StringBuffer synchronizes its methods for thread safety. In practice I use StringBuilder inside a method and never share it. If I need a shared mutable buffer across threads, which is rare, I synchronize or use StringBuffer deliberately.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.