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.