~/ learn/ comp-308/ cards/ Immutable Strings & StringBuilder
1 of 6

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/cf741a52-f10b-4704-98aa-ba1034b15997/flashcard utf-8 LF