Why should you avoid s += x for building a long string inside a big loop?
Options
- It is a syntax error when used inside a loop body
- Strings are immutable, so each
+=copies the old text (Correct option) - It converts the string to lowercase on every pass
- It only works with numbers, not with plain text
Answer
Strings are immutable, so each += creates a brand new String, copying all previous characters
Why
A String in Java can never change after creation (it is immutable). s += x really means: create a new String with the old text plus x, and throw the old one away.
In a loop with thousands of iterations that means thousands of copies, which is slow and creates garbage.
StringBuilder keeps an internal buffer that grows, so you append without copying every time. Call .toString() at the end.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(',');
}
String result = sb.toString();Remember
Many appends in a loop: use StringBuilder.