The Plain Picture#
Instead of reprinting a whole badge every time you add one letter, you use a whiteboard: write, add, erase, insert — all on the same board. When you're finished, print the final badge once.
The Real Names#
StringBuilderis a mutable sequence of characters: you change it in place. CalltoString()at the end to get aString.(
StringBufferis an older, thread-safe but slower version. UseStringBuilderunless you're sharing it across threads — which you almost never do.)
Under the Hood#
StringBuilder sb = new StringBuilder("study");
sb.append("buddy").insert(0, "[").append(']'); // methods return the builder, so calls can chain
System.out.println(sb); // [studybuddy]
sb.reverse();
System.out.println(sb); // ]yddubyduts[
sb.reverse();
sb.setCharAt(1, 'S');
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb + " " + sb.length()); // [Studybuddy 11
String finished = sb.toString();Why + in a loop is slow — measured#
Building a 50,000-character string one character at a time:
String slow = "";
for (int i = 0; i < 50_000; i++) slow += "x"; // a NEW string every round, copying everything so far
StringBuilder fast = new StringBuilder();
for (int i = 0; i < 50_000; i++) fast.append("x"); // adds to the same bufferReal timing on this Mac:
concat: 133 ms, builder: 0 ms, same=trueWhy: round k of the + loop copies k characters into a brand-new string, so the total work is 1 + 2 + … + n ≈ n²/2 character copies.
At n = 50,000 that's over a billion. StringBuilder keeps a growable internal array (like ArrayList, Collections, From the Inside)
and just adds to it, so the total is about n. In Big-O terms (Big-O and Complexity): O(n²) vs O(n). Double the input and the +
version takes four times as long.
(For a single expression like "Score: " + points + "/" + total, the compiler already optimises it; the problem is += inside loops.)
In DSA: building output, reversing strings, constructing answers character by character in backtracking
(Backtracking (coming soon)) — always StringBuilder.
Check yourself
3 questionsString vs StringBuilder — which is mutable?
Show answerHide answer
StringBuilder.
Why is result += piece inside a loop O(n²)?
Show answerHide answer
Each += builds a new String and copies everything so far; the copies add up to about n²/2.
How do you get a String out of a StringBuilder?
Show answerHide answer
sb.toString().