~/ 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/61155635-6595-4905-a14e-b83eff83d95a/flashcard utf-8 LF