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.
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
- 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 is 21 years... no, more! Java is fun Learning java is fun (length 20) ava is fun desserts
Joining in a loop
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
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.
compresscounts runs of equal characters and appends the character and its count; it returns the original if compression doesn't help.isPalindromekeeps 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 whytoString()is called before it on the left side.
Expected output
Running “Why StringBuilder matters, plus two text algorithms” prints exactly:
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
Prefer
Each += creates a new String and copies everything so far, making the loop quadratic.
Comparing builders with equals
Avoid
Prefer
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
- 1Reverse the order of words in a sentence using StringBuilder.
- 2Build 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?