×

java · level 2 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A grows text in place, piece by piece.

Strings are : they never change. text = text + "!" builds a brand new string and drops the old one. In a loop that runs thousands of times, that is thousands of new strings, made and thrown out.

A StringBuilder is text that can change. Make one with new StringBuilder(), then adds anything to the end: text, numbers, even objects. When you are finished, .toString() hands you the finished string.

It has tricks too: .length() counts the characters, and .reverse() flips the whole text back to front. Inside quotes, \n starts a new line, which is handy when you build text with several lines.

public class Main {
    public static void main(String[] args) {
        String[] guests = {"Ava", "Ben", "Cara"};
        StringBuilder card = new StringBuilder();
        card.append("Party guests:");
        for (String guest : guests) {
            card.append(" ").append(guest);
        }
        card.append(" (").append(guests.length).append(")");
        System.out.println(card.toString());
        System.out.println(new StringBuilder("stressed").reverse());
    }
}

.append hands the builder back, so you can chain calls, like .append(" ").append(guest).