typestar

StringBuilder in Java

Strings are immutable, so repeated concatenation copies; a builder does not.

// strings are immutable; a builder makes many appends cheap
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
    sb.append("step ").append(i).append('\n');
}
sb.insert(0, "the plan:\n");
System.out.println(sb);
System.out.println("length " + sb.length());

How it works

  1. append chains and grows the buffer in place.
  2. insert(0, ...) writes at any position, even the front.
  3. Printing the builder pays the string cost once, at the end.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
264
Tokens
85
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 54 seconds.

Type this snippet

Step 4 of 4 in Strings, step 7 of 29 in Language basics.

← Previous Next →

StringBuilder in other languages