Skip to lesson

String vs StringBuilder vs StringBuffer

A common test: "build a report of 10,000 order ids" or "reverse this string". The interviewer wants to hear which of String, StringBuilder and StringBuffer you pick, and why + inside a loop is the slow answer.

Comparison: mutability, thread safety and speed

StringBuilder is a mutable sequence of characters. Methods such as append, insert and reverse change the same object instead of creating new strings, so it is the default tool for building text.

The three types differ in mutability and locking. This program builds the same text with a String, a StringBuilder and a StringBuffer.

Example 1 · The three types side by side

Text
                 String          StringBuilder      StringBufferMutable?         no              yes                yesThread-safe?     yes (immutable) no                 yes (synchronized)Speed            new object      fastest            slower (locking)                 per changeSince            Java 1.0        Java 5             Java 1.0equals()         compares text   compares refs      compares refsUse for          fixed values,   building text in   one buffer shared                 map keys        a method           by threads (rare)
Rule
Default: String for values, StringBuilder for building.

What this code does

  • Draw this table when asked the difference; the interviewer usually follows up on one row, most often thread safety or equals.
  • "Thread-safe" for String comes from immutability; for StringBuffer it comes from locking each method.

StringBuffer has the same methods, but each one is synchronized, so only one thread runs it at a time. Use String for fixed values and map keys, StringBuilder for building text, and StringBuffer only when threads share one buffer. All three implement CharSequence.

Revise: StringBuilder (opens in a new tab)

Why + in a loop is slow

Each s = s + x copies every character built so far. This program builds the same text both ways and measures the time.

Example 2 · The same result, built two ways

ConcatInLoop.javaJava
public class ConcatInLoop {    public static void main(String[] args) {        String slow = "";        for (int i = 1; i <= 5; i++) {            slow = slow + i + ",";          // a new String object every time        }
        StringBuilder sb = new StringBuilder();        for (int i = 1; i <= 5; i++) {            sb.append(i).append(',');       // the same buffer, grown in place        }
        System.out.println(slow);        System.out.println(sb);        System.out.println(slow.equals(sb.toString()));    }}
Output
1,2,3,4,5,
1,2,3,4,5,
true

What this code does

  • Both loops produce the same text. The String loop creates a new object each time and copies everything built so far into it.
  • The builder version appends into one object; toString() creates the final String once at the end.

Example 3 · Measuring the difference

ConcatTiming.javaJava
public class ConcatTiming {    public static void main(String[] args) {        int n = 50_000;
        long start = System.nanoTime();        String s = "";        for (int i = 0; i < n; i++) {            s = s + 'x';        }        long plusMs = (System.nanoTime() - start) / 1_000_000;
        start = System.nanoTime();        StringBuilder sb = new StringBuilder();        for (int i = 0; i < n; i++) {            sb.append('x');        }        String built = sb.toString();        long builderMs = (System.nanoTime() - start) / 1_000_000;
        System.out.println("Same length: " + (s.length() == built.length()));        System.out.println("+ in loop:     " + plusMs + " ms");        System.out.println("StringBuilder: " + builderMs + " ms");    }}
Sample output
Same length: true
+ in loop:     312 ms
StringBuilder: 1 ms

What this code does

  • Your timings will differ by computer and JVM, but the builder is usually tens of times faster or more for 50,000 appends, and the gap grows with n, because the + loop does O(n²) copying.
  • This is a rough measurement for intuition only; real benchmarks need warm-up and a tool such as JMH.

After n steps that is about n²/2 character copies, which is O(n²), plus many short-lived objects for the garbage collector. A StringBuilder keeps one internal array with spare room and roughly doubles it when full, so the total work is O(n). The compiler optimises + inside one expression, but not across loop iterations.

Find the bug

Find the string-building bug

Each snippet has one wrong line. Tap it, then check the fix.

Build one CSV line of 10,000 order ids quickly.

Round 1 of 3

Methods interviewers ask about

These are the methods interviewers ask about. Indexes start at 0, and a range includes the start index but not the end index. This program uses each one once.

Example 4 · append, insert, replace, delete, reverse

BuilderMethods.javaJava
public class BuilderMethods {    public static void main(String[] args) {        StringBuilder sb = new StringBuilder("Jav");        sb.append('a').append(" ").append(17);        System.out.println(sb);
        sb.insert(0, "Learn ");        System.out.println(sb);
        sb.replace(6, 10, "JAVA");        System.out.println(sb);
        sb.deleteCharAt(sb.length() - 1);        System.out.println(sb);
        sb.delete(0, 6);        sb.setCharAt(0, 'j');        System.out.println(sb);
        sb.reverse();        String result = sb.toString();        System.out.println(result + " (length " + result.length() + ")");    }}
Output
Java 17
Learn Java 17
Learn JAVA 17
Learn JAVA 1
jAVA 1
1 AVAj (length 6)

What this code does

  • Every call changes the same object; chaining works because append returns the builder. replace(6, 10, ...) replaces indexes 6 to 9, the end index is excluded.
  • delete(0, 6) removes Learn , setCharAt changes one character in place, and reverse() flips the whole buffer before toString() makes a String.

Most modifying methods return the same builder, so calls can be chained. append(x) adds to the end and insert(i, x) adds before index i. delete(start, end), deleteCharAt(i), replace(start, end, text) and setCharAt(i, c) change content, and reverse() reverses in place. toString() creates the final String.

Predict the output

Predict the builder output

Read each snippet and pick what it prints.

Round 1 of 3

StringBuilder sb = new StringBuilder("Java 17");
sb.insert(0, "Learn ");
sb.replace(6, 10, "JAVA");
System.out.println(sb);

Coding question: reverse and palindrome

A palindrome is a text that reads the same forwards and backwards, such as madam. For sentences, interviewers usually ignore spaces, punctuation and upper or lower case.

First give the one-line built-in answer, then expect "now without reverse()". This program shows both, plus a two-pointer palindrome check.

Example 5 · Reverse and palindrome, with and without reverse()

PalindromeAnswer.javaJava
public class PalindromeAnswer {    static String reverseBuiltIn(String s) {        return new StringBuilder(s).reverse().toString();    }
    static String reverseManual(String s) {        char[] chars = s.toCharArray();        for (int i = 0, j = chars.length - 1; i < j; i++, j--) {            char tmp = chars[i];            chars[i] = chars[j];            chars[j] = tmp;        }        return new String(chars);    }
    static boolean isPalindrome(String s) {        String clean = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();        int i = 0, j = clean.length() - 1;        while (i < j) {            if (clean.charAt(i++) != clean.charAt(j--)) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        System.out.println(reverseBuiltIn("placement"));        System.out.println(reverseManual("placement"));        for (String s : new String[] {"Madam", "Never odd or even", "Java", ""}) {            System.out.println("[" + s + "] palindrome? " + isPalindrome(s));        }    }}
Output
tnemecalp
tnemecalp
[Madam] palindrome? true
[Never odd or even] palindrome? true
[Java] palindrome? false
[] palindrome? true

What this code does

  • Give reverseBuiltIn first, then reverseManual when asked to avoid built-ins: swap from both ends towards the middle, O(n) time.
  • isPalindrome removes everything except letters and digits, lower-cases, then compares with two pointers and stops at the first mismatch. An empty string counts as a palindrome; mention that edge case aloud.

Give new StringBuilder(s).reverse().toString() first. For the follow-up, swap characters from both ends of a char[], or compare with two pointers moving inwards. Both are O(n) time.

Order of execution

Reverse with two pointers

Put the steps in the order the code runs them.

Trap: StringBuilder does not override equals

Two builders with the same text are not equals. This program compares them four ways and shows which ones work.

Example 6 · Trap: two builders with the same text are not equal

BuilderEqualsTrap.javaJava
import java.util.HashSet;import java.util.Set;
public class BuilderEqualsTrap {    public static void main(String[] args) {        StringBuilder a = new StringBuilder("upi");        StringBuilder b = new StringBuilder("upi");
        System.out.println("a.equals(b): " + a.equals(b));        System.out.println("toString equals: " + a.toString().equals(b.toString()));        System.out.println("compareTo == 0: " + (a.compareTo(b) == 0));        System.out.println("contentEquals: " + "upi".contentEquals(a));
        Set<StringBuilder> set = new HashSet<>();        set.add(a);        set.add(b);        System.out.println("Set size: " + set.size());    }}
Output
a.equals(b): false
toString equals: true
compareTo == 0: true
contentEquals: true
Set size: 2

What this code does

  • equals is inherited from Object, so it compares references: false. The three content checks all say true; compareTo on StringBuilder needs Java 11 or later.
  • Because equals and hashCode are identity-based, the set keeps both builders. Convert to String before using text as a key or set element.

StringBuilder and StringBuffer inherit equals and hashCode from Object, which compare references, so a HashSet<StringBuilder> stores both. Compare content with toString().equals(...), contentEquals, or from Java 11 a.compareTo(b) == 0, and never use a builder as a map key.

toString() is overridden, which is why println(sb) prints the text but sb1.equals(sb2) still compares references.

Next step

Check your understanding

12 quick questions