Skip to content

Module 7 · Core Java APIs — topic 2 of 4

StringBuilder

Building and modifying text efficiently with StringBuilder: append, insert, delete, reverse, setCharAt, capacity, and why repeated string concatenation is slow.

Beginner 12 min read·Lesson 24 of 39 in Java Programming

Learning objectives

  • Build strings efficiently in loops with StringBuilder
  • Use append, insert, delete, replace, reverse and setCharAt
  • Explain why s += x in a loop is slow

Definition

StringBuilder is a mutable sequence of characters. Unlike String, its contents can be changed in place, making it efficient for building text piece by piece.

Introduction

Because String is immutable, every s += x creates a brand-new string and copies all the characters so far. Inside a loop of n iterations that is roughly n² character copies. StringBuilder keeps a resizable buffer instead, so appending is fast and the final toString() creates a single String.

Why it matters

Report generation, CSV/JSON output and string algorithms (reversing, building patterns) all need efficient text construction.

Interviewers often ask for the difference between String, StringBuilder and StringBuffer.

Detailed explanation

Creating. new StringBuilder(), new StringBuilder("start") or new StringBuilder(capacity) if you know the approximate final size.

Modifying methods change the builder in place and return the same builder, so calls can be chained: sb.append("a").append(1).append('!'). append accepts any type.

Other operations. insert(index, x), delete(start, end), deleteCharAt(i), replace(start, end, str), reverse(), setCharAt(i, c), setLength(n) (truncate or pad), charAt, indexOf and length.

Capacity. The internal buffer grows automatically (roughly doubling). Setting an initial capacity avoids repeated growth for very large outputs, but it is an optimisation, not a requirement.

toString() creates the final immutable String. A StringBuilder is not a String: you cannot pass it where a String is required without calling toString, and equals on two builders compares references.

StringBuffer is the older, synchronised (thread-safe) version. It is slower and rarely needed; use StringBuilder unless several threads share one buffer.

When not to bother. A single expression like "Hello " + name + "!" is already optimised by the compiler; StringBuilder matters inside loops.

Syntax

Java
StringBuilder sb = new StringBuilder();
sb.append("Total: ").append(42).append('\n'); // chaining
sb.insert(0, ">> ");
sb.reverse();
sb.setLength(0); // clear
String result = sb.toString();
  • Modifying methods return the same builder (fluent style).
  • Indexes follow the String rules: start inclusive, end exclusive.
  • Compare contents with sb1.toString().equals(sb2.toString()) or compareTo (Java 11).

Code examples

Building and editing text

Java
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is").append(' ').append(21).append(" years... no, more!");
System.out.println(sb);
sb.replace(8, sb.length(), "fun");
System.out.println(sb);
sb.insert(0, "Learning ");
sb.setCharAt(9, 'j');
System.out.println(sb + " (length " + sb.length() + ")");
sb.delete(0, 9).deleteCharAt(0);
System.out.println(sb);
System.out.println(new StringBuilder("stressed").reverse());
}
}
Output
Java is 21 years... no, more!
Java is fun
Learning java is fun (length 20)
ava is fun
desserts

Joining in a loop

Java
public class Main {
public static void main(String[] args) {
StringBuilder csv = new StringBuilder();
for (int i = 1; i <= 10; i++) {
if (csv.length() > 0) csv.append(',');
csv.append(i * i);
}
System.out.println(csv);
System.out.println(String.join(" | ", "a", "b", "c"));
}
}
Output
1,4,9,16,25,36,49,64,81,100
a | b | c

String.join is a convenient alternative when you already have the parts.

More examples

Why StringBuilder matters, plus two text algorithms

Java
public class Main {
static String compress(String s) { // "aaabccdddd" -> "a3b1c2d4"
StringBuilder out = new StringBuilder();
for (int i = 0; i < s.length(); ) {
char c = s.charAt(i);
int run = 0;
while (i < s.length() && s.charAt(i) == c) { i++; run++; }
out.append(c).append(run);
}
return out.length() < s.length() ? out.toString() : s;
}
static boolean isPalindrome(String s) {
StringBuilder letters = new StringBuilder();
for (char c : s.toCharArray()) if (Character.isLetterOrDigit(c)) letters.append(Character.toLowerCase(c));
return letters.toString().equals(letters.reverse().toString());
}
public static void main(String[] args) {
int n = 20_000;
long t0 = System.nanoTime();
String slow = "";
for (int i = 0; i < n; i++) slow += 'x';
long t1 = System.nanoTime();
StringBuilder fast = new StringBuilder();
for (int i = 0; i < n; i++) fast.append('x');
long t2 = System.nanoTime();
System.out.println("same result: " + slow.equals(fast.toString()));
System.out.println("StringBuilder was faster: " + (t2 - t1 < t1 - t0));
System.out.println(compress("aaabccdddd") + " " + compress("abc"));
System.out.println(isPalindrome("A man, a plan, a canal: Panama") + " " + isPalindrome("Java"));
}
}
Output
same result: true
StringBuilder was faster: true
a3b1c2d4 abc
true false

Step-by-step explanation

  • The first loop builds a 20,000-character string with +=, copying the whole string on every iteration.
  • The second loop appends to one StringBuilder, copying each character only when the buffer grows — dramatically faster.
  • compress counts runs of equal characters and appends the character and its count; it returns the original if compression doesn't help.
  • isPalindrome keeps only letters and digits in lower case, then compares the text with its reverse.
  • Note that letters.reverse() reverses the builder in place, which is why toString() is called before it on the left side.

Expected output

Running “Why StringBuilder matters, plus two text algorithms” prints exactly:

TextOutput
same result: true
StringBuilder was faster: true
a3b1c2d4 abc
true false

Practical applications

  • Generating reports, CSV and HTML output
  • Building SQL or log messages in loops
  • Text algorithms in interviews: reversing words, compression, palindromes

Best practices

  • Use StringBuilder for loops and String for single expressions.
  • Use String.join or Collectors.joining for simple joins.
  • Call toString once at the end.

Common mistakes

Concatenating with += in a big loop

Avoid

String s = "";
for (String line : lines) s += line + "\n";

Prefer

StringBuilder sb = new StringBuilder();
for (String line : lines) sb.append(line).append('\n');
String s = sb.toString();

Each += creates a new String and copies everything so far, making the loop quadratic.

Comparing builders with equals

Avoid

if (sb1.equals(sb2)) ...

Prefer

if (sb1.toString().equals(sb2.toString())) ...

StringBuilder doesn't override equals, so it compares references.

Important notes

  • Timing measurements vary from run to run; the example only checks which approach was faster, which is reliable at this size.
  • Since Java 9 the compiler implements + concatenation with invokedynamic, but that doesn't help repeated += in loops.

Key takeaways

  • StringBuilder is mutable; String is immutable.
  • Modifying methods return the builder, so calls can be chained.
  • Use StringBuilder when building strings in loops; StringBuffer only for shared threads.

Try it yourself

  1. 1
    Reverse the order of words in a sentence using StringBuilder.
  2. 2
    Build a multiplication table as one string and print it once.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy is StringBuilder better than s += x inside a large loop?
  • ModerateWhat is printed?
Practise this topic