Home › Learn › Java › Strings and text

StringBuilder

Lesson 23 of 40. Build long strings efficiently.

Each += on a string copies the whole string, so building a long string in a loop is slow. StringBuilder is a growable buffer: StringBuilder sb = new StringBuilder();, sb.append(x) adds anything (and returns the builder, so appends chain), sb.insert(0, x) adds at the front, sb.reverse() flips it in place, sb.length() and sb.setLength(n) measure and cut, and sb.toString() hands back the finished string.

The rule of thumb: a few joins, use +; a loop, use a StringBuilder.

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    sb.append(i).append(",");
}
sb.setLength(sb.length() - 1);   // drop the last comma
System.out.println(sb.toString());   // 1,2,3

Your task

Write static String reverse(String text) using a StringBuilder, static String repeat(String piece, int times) returning the piece joined to itself times times ("" for 0; do not use String.repeat), and static String numbered(String[] lines) returning the lines each prefixed with its 1-based number and a period and space, joined by \n ({"tea", "milk"} gives "1. tea\n2. milk").

Hint 1

return new StringBuilder(text).reverse().toString();

Hint 2

numbered: for (int i = 0; i < lines.length; i++) { if (i > 0) sb.append("\n"); sb.append(i + 1).append(". ").append(lines[i]); }

Show the solution
public class Main {
    static String reverse(String text) {
        return new StringBuilder(text).reverse().toString();
    }

    static String repeat(String piece, int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append(piece);
        }
        return sb.toString();
    }

    static String numbered(String[] lines) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {
            if (i > 0) {
                sb.append("\n");
            }
            sb.append(i + 1).append(". ").append(lines[i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverse("stressed") + " " + repeat("ab", 3));
        System.out.println(numbered(new String[]{"tea", "milk"}));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.