StringBuilder
Overview
While the String class is fantastic for storing static text, its Immutability makes it highly destructive to performance when you need to construct text dynamically in a loop.
Every time you concatenate strings using the + operator, Java abandons the old string and allocates memory for a brand new string. If you append characters in a loop 10,000 times, you create 10,000 dead string objects, forcing the Garbage Collector into overdrive.
StringBuilder solves this. It is a Mutable character array. It allows you to append, insert, or delete characters directly in the existing memory space without creating new objects, making it exponentially faster for dynamic string construction.
Syntax
Always default to StringBuilder when assembling strings piece by piece, especially inside loops or when reading large data streams.
public class Main {
public static void main(String[] args) {
// --- The WRONG Way (Performance Nightmare) ---
String slowStr = "";
for (int i = 0; i < 1000; i++) {
slowStr += i; // Creates 1000 abandoned objects!
}
// --- The RIGHT Way (Blazing Fast) ---
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i); // Modifies the same object 1000 times
}
// Convert back to an immutable String at the very end
String fastStr = sb.toString();
// Other useful mutable operations
StringBuilder word = new StringBuilder("Java");
word.reverse(); // "avaJ"
word.insert(0, "I Love "); // "I Love avaJ"
}
}Common Pitfalls
- Using
StringBufferinstead ofStringBuilder.StringBufferis the legacy version. It is heavily synchronized (thread-safe), which makes it significantly slower. Unless you are actively working in a multi-threaded environment sharing the exact same string builder, always useStringBuilder. - Forgetting to call
.toString()at the end. Many API methods require aString. You cannot pass aStringBuilderdirectly into them without converting it first.
Interview Questions
Standard String concatenation (+=) in a loop of N iterations takes O(N^2) time because it has to constantly recopy the ever-growing string. StringBuilder.append() takes O(N) time because it just adds characters to the end of a pre-allocated array.
It uses an internal dynamically sizing char[] array. It allocates extra buffer space. When you append, it simply places characters into the empty slots. If it runs out of space, it creates a new, larger array (usually double the size) and copies the characters over.
Real-World Example
Generating dynamic SQL Queries or HTML documents on a web server. Constructing a massive HTML email template based on user data requires appending hundreds of variables into a single text block.
StringBuilder html = new StringBuilder("<html><body>");
for(User u : users) {
html.append("<li>").append(u.getName()).append("</li>");
}
html.append("</body></html>");
return html.toString();Check Your Knowledge
Test your understanding of StringBuilder with these quick questions.