StringBuilder for Efficient Concatenation
Use StringBuilder to build strings efficiently inside loops and complex formatting.
StringBuilder for Efficient Concatenation is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
StringBuilder for Efficient Concatenation
StringBuilder is a mutable alternative to String for building text incrementally. It avoids creating many intermediate String objects.
StringBuilder vs String Concatenation
When concatenating many strings (especially in loops), StringBuilder is dramatically faster because it mutates an internal char buffer rather than creating new objects.
// Inefficient: creates a new String every iteration
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // 1000 new String objects!
}
// Efficient: StringBuilder uses a resizable char buffer
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(',');
}
String efficient = sb.toString(); // one final String createdStringBuilder API
Key methods: append, insert, delete, replace, reverse, toString, length, charAt, setCharAt.
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World"); // Hello, World
sb.insert(5, "!"); // Hello!, World
sb.delete(5, 6); // Hello, World
sb.replace(7, 12, "Java"); // Hello, Java
sb.reverse(); // avaJ ,olleH
sb.reverse(); // Hello, Java
System.out.println(sb); // Hello, Java
System.out.println(sb.length()); // 11
System.out.println(sb.charAt(0)); // HChaining append Calls
All append and other mutating methods return this, enabling fluent chaining.
StringBuilder html = new StringBuilder()
.append("<div class=\"card\">")
.append("<h2>").append("Product Title").append("</h2>")
.append("<p>Price: $").append(String.format("%.2f", 29.99)).append("</p>")
.append("<button>Add to Cart</button>")
.append("</div>");
System.out.println(html.toString());Initial Capacity
Pre-size the StringBuilder with an expected capacity to avoid internal array resizing, improving performance for large strings.
// Default capacity: 16 chars
StringBuilder small = new StringBuilder();
// Pre-sized: 10 items * ~50 chars each
StringBuilder report = new StringBuilder(500);
for (int i = 1; i <= 10; i++) {
report.append(String.format("%-3d. Record %04d: processed OK%n", i, i));
}
System.out.println(report.toString().substring(0, 30));
// " 1. Record 0001: processed OK"deleteCharAt and specific deletions
deleteCharAt removes a single character. delete(start, end) removes a range. These are O(n) due to array shifting.
StringBuilder sb = new StringBuilder("Hello, World!");
sb.deleteCharAt(5); // removes comma: "Hello World!"
sb.delete(5, 6); // removes space: "HelloWorld!"
System.out.println(sb); // HelloWorld!
// Replace to fix a typo
StringBuilder typo = new StringBuilder("Helo, Java!");
typo.replace(typo.indexOf("Helo"), typo.indexOf("Helo") + 4, "Hello");
System.out.println(typo); // Hello, Java!Building CSV
A practical pattern: building a CSV line with StringBuilder and proper separator handling.
import java.util.List;
static String toCsv(List<String> values) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) sb.append(',');
sb.append(escapeCsv(values.get(i)));
}
return sb.toString();
}
static String escapeCsv(String s) {
if (s.contains(",") || s.contains("\""))
return "\"" + s.replace("\"", "\"\"") + "\"";
return s;
}
System.out.println(toCsv(List.of("Alice", "Smith, Jr.", "30")));
// Alice,"Smith, Jr.",30StringJoiner for Delimiter-Separated Output
StringJoiner simplifies joining elements with a delimiter, optional prefix and suffix — no manual separator handling needed.
import java.util.StringJoiner;
StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.add("Alice");
sj.add("Bob");
sj.add("Charlie");
System.out.println(sj.toString()); // [Alice, Bob, Charlie]
// Equivalent with String.join
String joined = String.join(", ", "Alice", "Bob", "Charlie");
System.out.println(joined); // Alice, Bob, Charlie
// Streams: collect with joining collector
import java.util.stream.*;
List.of("a", "b", "c").stream()
.collect(Collectors.joining(", ", "(", ")"));
// (a, b, c)StringBuilder vs StringBuffer
StringBuffer is the thread-safe, synchronized version of StringBuilder. It's slower due to locking. Use StringBuilder in single-threaded contexts (99% of cases).
// StringBuffer: thread-safe but slower (synchronized methods)
StringBuffer buf = new StringBuffer();
buf.append("Thread-safe");
buf.append(" but slow");
// StringBuilder: not thread-safe but faster
StringBuilder sb = new StringBuilder();
sb.append("Fast");
sb.append(" single-threaded");
// When to use StringBuffer:
// - Multiple threads write to the same buffer
// - Almost always a design smell — redesign to avoid sharingReversing and Palindrome Check
StringBuilder's built-in reverse() makes palindrome checking elegant.
static boolean isPalindrome(String s) {
String cleaned = s.toLowerCase()
.replaceAll("[^a-z0-9]", ""); // remove non-alphanumeric
String reversed = new StringBuilder(cleaned).reverse().toString();
return cleaned.equals(reversed);
}
System.out.println(isPalindrome("A man, a plan, a canal: Panama")); // true
System.out.println(isPalindrome("race a car")); // false
System.out.println(isPalindrome("Was it a car or a cat I saw?")); // trueReal-World: SQL Query Builder
Building a dynamic SQL query using StringBuilder where clauses are added conditionally.
static String buildQuery(String category, Double minPrice, Double maxPrice) {
StringBuilder sql = new StringBuilder("SELECT * FROM products WHERE 1=1");
if (category != null)
sql.append(" AND category = '" + category + "'");
if (minPrice != null)
sql.append(" AND price >= ").append(minPrice);
if (maxPrice != null)
sql.append(" AND price <= ").append(maxPrice);
sql.append(" ORDER BY name");
return sql.toString();
}
System.out.println(buildQuery("Electronics", 50.0, null));
// SELECT * FROM products WHERE 1=1 AND category = 'Electronics' AND price >= 50.0 ORDER BY nameQuick Check
Why is string concatenation with + inefficient in loops?
Recap: StringBuilder for Efficient Concatenation
Key takeaways:
- StringBuilder is mutable — append/insert/delete mutate an internal buffer
- Use StringBuilder in loops to avoid O(n²) string creation
- All mutating methods return this — enabling fluent chaining
- Pre-size StringBuilder with expected capacity to reduce internal resizing
- StringJoiner and String.join are convenient for delimiter-separated output
- StringBuffer is the synchronized (thread-safe) but slower alternative
Frequently asked questions
Is the “StringBuilder for Efficient Concatenation” lesson free?
Yes — the full text of “StringBuilder for Efficient Concatenation” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “StringBuilder for Efficient Concatenation”?
Use StringBuilder to build strings efficiently inside loops and complex formatting. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “StringBuilder for Efficient Concatenation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- String Immutability and the String Pool
- StringBuilder for Efficient Concatenation
- Text Blocks and String.format
- Regular Expressions with Pattern and Matcher