AI Hints
Home›Java Tutorial›StringBuilder, Dates and Times, Packages and Imports
Java · Lesson 109 of 120

StringBuilder

Build text efficiently.

⏱ 2 min read▶ Video at 2:19:03🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Strings can't change. So joining strings in a loop makes a brand new string every time. A StringBuilder is a piece of text that can change, so building long text is fast.

  • Strings can't change
  • + in a loop is slow
  • StringBuilder can change

Building text

Append adds to the end, without making a new string. Here, we build one, dash, two, and so on. Insert puts text at a position. Reverse flips the whole thing. Run it. The counting line, then the same line, reversed. Level reversed is still level. And the builder holds twenty four characters.

Main.javajava
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);
        sb.insert(0, "Count: ");
        sb.reverse();
        System.out.println(sb);
        System.out.println(new StringBuilder("level").reverse() + " " + sb.length());
    }
}
Output
1 - 2 - 3 - 4 - 5
5 - 4 - 3 - 2 - 1 :tnuoC
level 24

Is it really faster?

We build a long string twice. First with plus, then with a StringBuilder. Nano time measures how long each one takes. Run it. Both made twenty thousand letters. And the StringBuilder was faster.

Main.javajava
public class Main {
    public static void main(String[] args) {
        long t1 = System.nanoTime();
        String s = "";
        for (int i = 0; i < 20000; i++) s += "x";
        long t2 = System.nanoTime();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20000; i++) sb.append("x");
        long t3 = System.nanoTime();
        System.out.println("Both made " + s.length() + " and " + sb.length() + " letters");
        System.out.println("StringBuilder was faster? " + ((t3 - t2) < (t2 - t1)));
    }
}
Output
Both made 20000 and 20000 letters
StringBuilder was faster? true

When to use it

Use plus for a few joins, it's clear and fine. Use a StringBuilder when you join inside a loop. Call to string at the end, when you need a String. And remember, String dot join, and Collectors dot joining, are great too.

keyvalue
A few joins+ is fine
In a loopStringBuilder
Finishsb.toString()
AlsoString.join, joining()

Summary

A StringBuilder is changeable text. Append, insert, and reverse change it in place. Use it when building text in a loop. Next, dates and times.

Key takeaways
  • append, insert
  • reverse
  • Use in loops
Next up: Dates and Times — java.time