How StringBuilder Works — API Cheat Sheet
No exercise here — how to build up a string efficiently in a loop across Java, C#, Python, and JavaScript/TypeScript, without accidentally writing O(n^2) code.
This is a reference page, not a graded exercise. Strings are immutable everywhere (see the Strings cheat sheet) — so result = result + piece inside a loop doesn't append, it allocates a brand-new string and copies everything over, every single iteration. Do that n times and an O(n) job becomes O(n^2). This page is about the fix.
Java — StringBuilder
| Want to... | Method | Example |
|---|---|---|
| Create | new StringBuilder() | |
| Append | .append(x) | works on strings, chars, numbers — overloaded for everything |
| Insert at an index | .insert(i, x) | |
| Delete a range | .delete(start, end) / .deleteCharAt(i) | |
| Reverse | .reverse() | in place |
| Length | .length() | |
| Finish | .toString() | converts back to an immutable String |
C# — StringBuilder
| Want to... | Method | Example |
|---|---|---|
| Create | new StringBuilder() | using System.Text; |
| Append | .Append(x) | |
| Insert at an index | .Insert(i, x) | |
| Remove a range | .Remove(start, length) | second arg is length, not end index |
| Length | .Length | property |
| Finish | .ToString() |
Python — no StringBuilder class, use a list + join
| Want to... | Pattern | Example |
|---|---|---|
| "Append" | append pieces to a list | parts = []; parts.append(piece) |
| Finish | "".join(parts) | joins all at once — O(n) total, not O(n^2) |
| Alternative | io.StringIO() | has a .write(x) method if you prefer a stream-like API; call .getvalue() at the end |
JavaScript / TypeScript — no StringBuilder class either
| Want to... | Pattern | Example |
|---|---|---|
| "Append" | push pieces into an array | const parts = []; parts.push(piece); |
| Finish | parts.join("") | |
| Note | Modern JS engines (V8) actually optimize simple str += piece loops reasonably well internally, so plain concatenation isn't the O(n^2) trap here that it is in Java/C# without a builder — but array.push + .join is still the idiomatic, engine-independent answer, and the one to reach for if asked to reason about complexity. |
The gotcha that costs the most time: it's not about whether your code produces the right output — result += piece in a loop gives the correct string in every language here. It's about complexity: if an interviewer asks "what's the time complexity of building this string," and you've been concatenating immutable strings in a loop in Java or C#, the honest answer is O(n^2), not O(n) — and StringBuilder/list-and-join is the fix.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.