StringBuilder
Overview
We know that normal Strings are Immutable (cannot be changed). Every time you do `text = text + "a"`, Java creates a brand new String and throws the old one out.
Imagine doing this in a loop 10,000 times! Java would create 10,000 strings, suffocating your computer's memory and slowing the app to a crawl.
Enter StringBuilder. It is a mutable (changeable) sequence of text. It acts like an expanding bucket. You can toss characters in, delete them, or reverse them instantly without creating new objects.
1. When to use it?
If you are just combining two strings together once, a normal `+` is fine. But if you are building a string dynamically inside a Loop, you MUST use StringBuilder for performance.
2. The append() method
Instead of using `+`, StringBuilder uses the `.append()` method to stick new text to the end of the bucket.
3. Powerful Mutations
StringBuilder lets you `.insert()` text into the middle, `.delete()` chunks, or `.reverse()` the whole thing instantly.
Syntax
See how StringBuilder safely modifies a single object instead of creating 100.
// ❌ BAD: Very slow inside a loop
String badResult = "";
for (int i = 0; i < 100; i++) {
badResult += i;
}
// ✅ GOOD: Lightning fast memory management
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append(i);
}
// When finished, convert the builder back to a normal String
String finalResult = sb.toString();StringBuilder provides powerful tools you don't get with normal Strings.
StringBuilder word = new StringBuilder("Java");
word.append(" is cool"); // "Java is cool"
word.insert(4, " script"); // "Java script is cool"
word.delete(5, 11); // "Java is cool"
word.reverse(); // "looc si avaJ"Common Pitfalls
- Forgetting to call `.toString()` at the end. Most methods in Java expect a `String`, not a `StringBuilder` object.
- Using `StringBuffer` instead. `StringBuffer` is an older, slower version of `StringBuilder`. Always use `StringBuilder` unless you are dealing with multithreading.
Interview Tips
- If you are asked an algorithm question like 'Reverse this string' or 'Build a CSV file', always use `StringBuilder` to show you understand memory optimization.
Real-World Example
Generating dynamic text formats, like creating a comma-separated list of items from a database.
public class ReportGenerator {
public static void main(String[] args) {
String[] purchasedItems = {"Laptop", "Mouse", "Keyboard"};
StringBuilder report = new StringBuilder();
report.append("Your order contains: ");
for (String item : purchasedItems) {
report.append(item).append(", ");
}
System.out.println(report.toString());
}
}