Memra

StringBuilder: efficient text assembly

When immutability gets expensive, build mutably.

Building strings in a loop

Because Strings are immutable, concatenating in a loop creates a new String every iteration — O(n²) work. StringBuilder is a mutable buffer built for this:

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append("row ").append(i).append('\n');
}
String result = sb.toString();

append(...) returns the same builder, so calls chain. Other handy methods: insert(pos, x), reverse(), delete(a, b), length(), and toString() to get the final String.

Rule of thumb: a few + concatenations are fine and readable; assembling text in a loop is the signal to reach for StringBuilder.

NORMAL ~/memra/learn/java-from-zero/stringbuilder utf-8 LF