Learn Java · lesson 35 of 61 · about 8 minutes
StringBuilder
List the group's seats: build text efficiently with StringBuilder instead of repeated + in a loop.
What you'll learn
- Append with StringBuilder
- Insert and reverse text
- Turn it back into a String
The group's seats
The receipt should list every seat the group has, like Your seats: C1, C2, C3. Seats go 12 to a row starting at row C, so seat i (counting from 0) is in row (char) (row + i / 12) with number i % 12 + 1, and a group of 14 runs on to D1, D2. The labels are added one at a time to a StringBuilder, with ", " added before every seat except the first, so there's no comma left over at the end.
Why not +=?
Strings can't change, so s += x builds a brand-new String every time. In a long loop that's slow.
StringBuilder is a changeable buffer:
sb.append(x)adds to the endsb.insert(i, x)adds at position isb.reverse()reverses itsb.toString()gives the final String
Building and reversing
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i);
if (i < 5) sb.append("-");
}
System.out.println(sb);
String word = new StringBuilder("stressed").reverse().toString();
System.out.println(word);
System.out.println(new StringBuilder("Java").insert(0, "I love ").append("!"));
}
}Output
1-2-3-4-5
desserts
I love Java!A comma between, not after
Adding ", " after every item leaves one hanging at the end. Adding it before every item except the first doesn't: if (sb.length() > 0) sb.append(", "); is true for every item but the first, because the builder is still empty then.
Seats in a row
public class Main {
public static void main(String[] args) {
StringBuilder seats = new StringBuilder();
for (int n = 1; n <= 3; n++) {
if (seats.length() > 0) {
seats.append(", ");
}
seats.append('C').append(n);
}
System.out.println(seats);
}
}Output
C1, C2, C3Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.