Skip to main content

String vs StringBuilder vs StringBuffer in Java

7 min readUpdated

All three hold text, but they behave differently when the text changes. String never changes, StringBuilder changes in place and is fast, and StringBuffer is the older, synchronized version. Here is when to use which.

The short answer

  • Use String for text that does not change: names, messages, keys.
  • Use StringBuilder to build text step by step, especially in loops.
  • You almost never need StringBuffer; it is a synchronized StringBuilder kept for old code.
StringStringBuilderStringBuffer
Can change after creationNo (immutable)YesYes
Thread safeYes (because immutable)NoYes (synchronized methods)
Speed when building textSlow in loops (new object every time)FastA little slower than StringBuilder
SinceJava 1.0Java 5Java 1.0
equals() compares contentYesNo (reference)No (reference)
Typical useMost textBuilding text in a loopLegacy code

String is immutable

Methods such as toUpperCase(), replace() and concat() never change the string; they return a new one. If you ignore the return value, nothing happens.

String methods return new strings; StringBuilder changes itself
public class Immutable {
    public static void main(String[] args) {
        String name = "java";
        name.toUpperCase();          // result thrown away
        System.out.println(name);
        name = name.toUpperCase();   // keep the new string
        System.out.println(name);

        StringBuilder sb = new StringBuilder("java");
        sb.append(" 21").insert(0, "I use ");
        System.out.println(sb);      // the same object, changed in place
    }
}

Output

java
JAVA
I use java 21

Why += in a loop is slow

Each s += x on a String creates a new string and copies all the characters so far. In a loop of n steps that is about n²/2 character copies. StringBuilder keeps one growing buffer, so the same loop is linear.

Build text with StringBuilder or String.join
public class BuildText {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            if (sb.length() > 0) sb.append(", ");
            sb.append(i * i);
        }
        System.out.println(sb.toString());

        // For joining a list there is an even simpler way:
        System.out.println(String.join(" | ", "red", "green", "blue"));
    }
}

Output

1, 4, 9, 16, 25
red | green | blue

For a single line such as "Hello " + name + "!", plain + is fine: the compiler already turns it into efficient code. The problem is only += inside loops.

Useful StringBuilder methods

MethodWhat it does
append(x)Adds x at the end (any type)
insert(i, x)Inserts x at index i
delete(start, end) / deleteCharAt(i)Removes characters
reverse()Reverses the text in place
setCharAt(i, c)Replaces one character
setLength(0)Clears it for reuse
toString()Returns the final String

Why String is immutable

  • String pool: literals can be shared safely because no one can change them.
  • Security: a file path or URL checked once cannot be changed afterwards.
  • Hash keys: the hash code is computed once and cached, which makes strings fast HashMap keys.
  • Thread safety: strings can be shared between threads with no locking.

Common mistakes

  • Calling name.trim() or name.replace(...) without assigning the result.
  • Comparing a StringBuilder with equals(). It compares references; call toString() first, or compareTo() (Java 11+).
  • Using StringBuffer in new code "to be safe". If several threads really build one text together, rethink the design.
  • Building SQL with string concatenation. Use PreparedStatement parameters instead.

Frequently asked questions

Which is faster, StringBuilder or StringBuffer?

StringBuilder, because its methods are not synchronized. The difference is small, but there is no reason to pay it in single-threaded code.

Is StringBuilder thread safe?

No. If several threads change the same StringBuilder, the result can be corrupted. In practice, build text in one thread and share the finished String.

Why is String immutable in Java?

So that strings can be shared safely in the string pool and between threads, used as stable HashMap keys, and trusted after security checks.

Try it yourself

Write and run Java code in the free online compiler, or press Visualize to watch it run line by line. Nothing to install.

Practise this, step by step

Short lessons with quizzes, practice and interview questions, from your first program to job-ready.

Java Programming course: syllabus and 1:1 mentoringCore Java from zero to OOP, collections, streams, files and threads.