Building Text with StringBuilder

Why StringBuilder?

Strings can't change, so every + makes a brand-new string. That's fine for a few joins, but slow when you build text bit by bit many times. A StringBuilder is text you can change.

Think of it like this: A String is like a printed page – to change it you must print a new page. A StringBuilder is like a whiteboard – you can keep adding and rubbing out.

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(", ");
        sb.append("World");
        sb.append('!');
        System.out.println(sb.toString());
        System.out.println(sb.length());
    }
}

Output

Hello, World!
13

More StringBuilder tools

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.reverse();
        System.out.println(sb);
        sb.reverse();
        sb.insert(0, "I love ");
        System.out.println(sb);
        sb.setCharAt(0, 'U');
        System.out.println(sb);
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb);
    }
}

Output

avaJ
I love Java
U love Java
U love Jav

Remember: Call .toString() to turn a StringBuilder back into a normal String.

HOME LABS COMMUNITY DASHBOARD