Stop 02 · Variables, Data Types & OperatorsTopics · 6/7

StringBuilder

Part of the Java Roadmap

In short

Because Strings never change, building text with + inside a loop quietly creates a new object every time. StringBuilder gives you one editable buffer instead, and it is the standard answer to "how do you build strings efficiently in Java?"

String objects cannot change, so joining strings in a loop creates many throwaway objects. StringBuilder is a mutable buffer with append, insert, reverse and toString that makes repeated edits efficient.

The jaadu happily scribbles and erases on one big whiteboard while a tall wobbly pile of crumpled paper sheets sits in a bin beside it.

Think of it like this

A whiteboard vs printed notices

If every change to a notice means printing a fresh sheet, a busy office drowns in paper. A whiteboard lets you add, erase and rewrite on the same surface. String is the printed notice; StringBuilder is the whiteboard. When you are done, you take one clean photo of it with toString().

Watch it happen

Building text in a loop of 10,000 steps

String with +

  • Each += creates a brand-new String
  • Old copies pile up for the garbage collector
  • Work grows roughly with the square of the length

StringBuilder

  • One resizable buffer, edited in place
  • append, insert, delete, reverse
  • Call toString() once at the end

For a few joins on one line, + is fine and readable. Inside loops, use StringBuilder.

The big ideas

What you need to know

Mutable

append and insert change the same object. No need to reassign the variable.

Chainable

Each method returns the builder, so you can write sb.append(a).append(", ").append(b);

Use in loops

Building a report, CSV line or receipt in a loop is the classic use.

Handy extras

reverse(), setCharAt(), deleteCharAt() and setLength(0) to clear and reuse.

See it in code

Walk through the code

java
1public class Receipt {2    public static void main(String[] args) {3        String[] items = {"Idli", "Vada", "Filter Coffee"};4        int[] prices = {40, 35, 25};5 6        StringBuilder sb = new StringBuilder();7        sb.append("--- Sharma Tiffin Centre ---").append(System.lineSeparator());8 9        int total = 0;10        for (int i = 0; i < items.length; i++) {11            sb.append(items[i]).append(": ₹").append(prices[i])12              .append(System.lineSeparator());13            total += prices[i];14        }15        sb.append("Total: ₹").append(total);16 17        System.out.println(sb.toString());18        System.out.println(new StringBuilder("level").reverse());19    }20}

1/5One builder for the whole receipt.

A receipt built line by line in one buffer, plus the classic reverse trick for palindromes.

Save yourself the pain

Common mistakes

Oops

Comparing two builders with equals to check their text.

Do this instead

StringBuilder does not override equals. Compare sb1.toString().equals(sb2.toString()), or use sb1.compareTo(sb2) == 0 on Java 11+.

Oops

Replacing every + in the code with StringBuilder.

Do this instead

For a single expression like "Hi " + name, + is clearer and the compiler optimises it. Save StringBuilder for loops.

Your mission

Times table builder

~15 min

Quick check

Why is StringBuilder preferred for joining text inside a long loop?

Go deeper

  1. 1Build a 1 to 100 number list with StringBuilder instead of + in a loop.
  2. 2Reverse a string using StringBuilder.reverse() and check if it is a palindrome.
  3. 3Time 10,000 string concatenations with + versus StringBuilder.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge