# String vs StringBuilder vs StringBuffer

> What are the differences between String, StringBuilder and StringBuffer, and when would you use each?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-string-stringbuilder-stringbuffer
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What are the differences between String, StringBuilder and StringBuffer, and when would you use each?

## Answer

This is a classic warm-up, and the trap is that many candidates answer with a one-line table and stop. Let me give you the reasoning so you can answer the follow-ups too.

Start with String. It is immutable, so every modification produces a new object. That is perfect for constants, map keys and anything shared across threads, but it is expensive when you build text piece by piece. If you write s = s + i inside a loop of 10,000 iterations, each iteration allocates a new String and copies all previous characters. That is O(n squared) work overall and a lot of garbage.

StringBuilder fixes this. It is a mutable sequence of characters backed by an internal array that grows as needed. Calling append writes into the same buffer, only resizing occasionally (the capacity roughly doubles plus two each time). So building a string of n characters is O(n) overall. StringBuilder is not synchronized, so it is fast but not safe if several threads modify the same instance.

StringBuffer is the same API as StringBuilder but every public method is synchronized. It was in Java 1.0, while StringBuilder arrived in Java 5 as the unsynchronized twin. Because synchronization costs time and, more importantly, because you rarely share a string-building buffer between threads, StringBuffer is almost never the right choice today. Even when threads are involved, synchronizing individual methods does not make a sequence of operations atomic, so you would still need your own locking.

So the summary: String when the value does not change, StringBuilder for building text within one thread (the 95 percent case), StringBuffer only for legacy code or a genuinely shared buffer.

Here are the edge cases interviewers love. First, the compiler already optimizes simple concatenation. A statement like String s = "a" + b + "c" outside loops is compiled into StringBuilder calls (or invokedynamic with StringConcatFactory since Java 9), so do not obsess over it. The problem appears in loops, because a fresh builder is created per iteration.

Second, equals is not overridden in StringBuilder or StringBuffer. new StringBuilder("a").equals(new StringBuilder("a")) is false because it uses identity. To compare content, call toString first or use compareTo (available since Java 11).

Third, you can pre-size the builder with new StringBuilder(capacity) when you know roughly the final length, avoiding repeated array copying.

Fourth, StringBuilder has handy mutation methods that String lacks: reverse, insert, deleteCharAt, setCharAt and replace. The classic string reverse or palindrome question is easy with reverse.

Fifth, memory: builders are not pooled. There is no literal syntax for them, so they always live on the heap as ordinary objects.

Also mention that String.join and the streams Collectors.joining are convenient alternatives for joining collections, and they use StringBuilder internally. In a real project, I would reach for those before hand-rolling a loop.

## Code examples

### Mutability and equality of the three types

```
public class BuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("abc");
        sb.append("def").reverse().insert(0, "X");
        System.out.println(sb);

        StringBuilder p = new StringBuilder("a");
        StringBuilder q = new StringBuilder("a");
        System.out.println(p.equals(q));
        System.out.println(p.toString().equals(q.toString()));

        StringBuffer safe = new StringBuffer("sync");
        safe.append(1).append(true);
        System.out.println(safe);

        String s = "";
        for (int i = 0; i < 3; i++) {
            s += i;
        }
        System.out.println(s);
    }
}
```

reverse turns abcdef into fedcba, then insert puts X at index 0. equals on builders is identity based, so compare toString results for content.

## Key points

- String is immutable; StringBuilder and StringBuffer are mutable.
- StringBuffer is synchronized and slower; StringBuilder is not synchronized.
- Never concatenate with + inside a loop; use StringBuilder.
- StringBuilder and StringBuffer do not override equals or hashCode.

## Common follow-up questions

- How would you reverse a string in Java without using reverse()?
- What is the default capacity of a StringBuilder?
- Does string concatenation with + use StringBuilder internally?
- How does String.join work?

## Interview tips

- Mention that synchronizing each method does not make compound operations atomic. It shows you understand why StringBuffer fell out of favour.
- If asked for performance, say O(n squared) for repeated concatenation versus O(n) with a builder.

## Concepts covered

String, StringBuilder, StringBuffer, Thread Safety, Performance

Previous: [String Immutability and the String Pool](https://www.internhack.in/learn/interview/java-interview/java-string-immutability-pool) · Next: [== vs equals() and the hashCode Contract](https://www.internhack.in/learn/interview/java-interview/java-equals-hashcode-contract) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [final vs finally vs finalize](https://www.internhack.in/learn/interview/java-interview/java-final-finally-finalize)
- [The static Keyword: Variables, Methods, Blocks and Nested Classes](https://www.internhack.in/learn/interview/java-interview/java-static-keyword)
- [Wrapper Classes, Autoboxing and the Integer Cache](https://www.internhack.in/learn/interview/java-interview/java-wrapper-autoboxing-integer-cache)
- [Checked vs Unchecked Exceptions](https://www.internhack.in/learn/interview/java-interview/java-checked-vs-unchecked-exceptions)
- [try-with-resources and AutoCloseable](https://www.internhack.in/learn/interview/java-interview/java-try-with-resources)
- [The Java Collections Framework Hierarchy](https://www.internhack.in/learn/interview/java-interview/java-collections-hierarchy)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
