StringBuilder
Build and modify strings efficiently using StringBuilder - the mutable alternative to immutable String.
Overview
Key Points
- •StringBuilder is mutable - append(), insert(), delete(), reverse() modify the same object
- •append(x) adds to the end - works with any type (int, double, char, String, boolean)
- •insert(index, x) - inserts at a specific position
- •delete(start, end) - removes characters from start (inclusive) to end (exclusive)
- •reverse() - reverses the entire content
- •toString() - converts back to an immutable String when done
- •Prefer StringBuilder inside loops; use + for short one-off concatenations
Examples
Basic StringBuilder usage
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("World");
sb.append("!");
System.out.println(sb.toString()); // Hello, World!
System.out.println(sb.length()); // 13
// append() returns the StringBuilder - chain calls
StringBuilder chained = new StringBuilder()
.append("Java ")
.append(21)
.append(" is great!");
System.out.println(chained); // Java 21 is great!
}
}You can print a StringBuilder directly - toString() is called automatically.
insert, delete, reverse, replace
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, ","); // Hello, World
System.out.println(sb);
sb.delete(0, 6); // World
System.out.println(sb);
sb.reverse(); // dlroW
System.out.println(sb);
sb.replace(0, 5, "Java"); // Java (replace all of "dlroW" with "Java")
System.out.println(sb);
}
}All these methods modify sb in place and return the StringBuilder itself.
Performance: StringBuilder vs String in a loop
public class Main {
public static void main(String[] args) {
// SLOW: creates 10,000 intermediate String objects
String slow = "";
for (int i = 0; i < 10_000; i++) {
slow += i;
}
// FAST: one StringBuilder, one buffer
StringBuilder fast = new StringBuilder();
for (int i = 0; i < 10_000; i++) {
fast.append(i);
}
String result = fast.toString();
System.out.println("Built " + result.length() + " characters");
}
}String concatenation in a loop is O(n²). StringBuilder is O(n). Use it inside loops.
Common Mistakes
- Using String + concatenation in a large loop - use StringBuilder.append() instead
- Calling toString() on every append instead of once at the end
- Confusing StringBuilder with StringBuffer - StringBuffer is thread-safe but slower; use StringBuilder in single-threaded code
Note
Modern Java compilers sometimes optimise simple + concatenation into StringBuilder automatically - but only in simple cases. Be explicit with StringBuilder inside loops or when building long strings.
Exercises
Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.
Completed: 0 / 4 exercises
Knowledge Check
Question 1 of 4