~/ learn/ comp-308/ cards/ Strings, Regex & Formatting
1 of 24

Type the right way to build a string in a loop

Type the right way to build a string in a loop

Answer

StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) { if (i > 0) sb.append('-'); sb.append(i); } String result = sb.toString();

One mutable buffer is appended in place; toString() materializes the final String once. Compare to s = s + i in a loop, which allocates a fresh String every iteration.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e7932c93-b1e8-4e8f-8704-ad687296b92b/flashcard utf-8 LF