Lesson 2 of 10
StringBuilder - Efficient String Building
StringBuilder is a mutable sequence of characters - unlike String, it doesn't create a new object on each change. For building strings in loops, generating reports, or constructing large text, StringBuilder is the correct tool.
StringBuilder vs String Concatenation
public class StringBuilderDemo {
public static void main(String[] args) {
// ❌ BAD: String + in loop = O(N²) object creation
// Compiler optimises single-line concatenation but NOT loops
String result = "";
for (int i = 1; i <= 100; i++) {
result += i + ", "; // creates 100 temporary String objects!
}
// ✅ GOOD: StringBuilder - O(N) amortised
StringBuilder sb = new StringBuilder(256); // initial capacity hint
for (int i = 1; i <= 100; i++) {
sb.append(i);
if (i < 100) sb.append(", ");
}
String output = sb.toString(); // convert only when done
// StringBuilder methods
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World"); // "Hello World"
builder.insert(5, ","); // "Hello, World"
builder.delete(5, 6); // "Hello World"
builder.replace(6, 11, "Java"); // "Hello Java"
builder.reverse(); // "avaJ olleH"
builder.reverse(); // "Hello Java"
// Remove trailing separator pattern
StringBuilder csv = new StringBuilder();
String[] items = {"Apple", "Banana", "Cherry"};
for (String item : items) {
csv.append(item).append(", ");
}
csv.setLength(csv.length() - 2); // trim last ", "
System.out.println(csv); // Apple, Banana, Cherry
// StringJoiner (Java 8+) - clean way to join with delimiter
var joiner = new java.util.StringJoiner(", ", "[", "]");
joiner.add("Java").add("Python").add("Go");
System.out.println(joiner); // [Java, Python, Go]
}
}Quick Quiz
Tip
Tip
Practice StringBuilder Efficient String Building in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for StringBuilder - Efficient String Building
Practice Task
Note
Practice Task - (1) Write a working example of StringBuilder Efficient String Building from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with StringBuilder Efficient String Building is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?