Skip to content
Veltoryx Technologies
ProLesson 3.4Beginner3 min readUpdated 30 October 2026

StringBuilder and StringBuffer

Build text efficiently with StringBuilder, see why + in a loop is slow, and know when StringBuffer is the right choice.

Because Strings can't change, every + creates a brand new String. That's fine for a few joins. In a loop it gets slow, because Java keeps copying the whole text. StringBuilder fixes this: it's a text buffer you can change.

01Using StringBuilder

Builder.java
public class Builder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Order #").append(1042).append(": ");
        sb.append("3 items");
        sb.insert(0, "[OK] ");
        System.out.println(sb);
        sb.reverse();
        System.out.println(sb);
        sb.reverse().setLength(5);   // keep the first 5 characters
        System.out.println(sb);
        String result = sb.toString();   // turn it back into a String
        System.out.println(result.length());
    }
}
Expected output
[OK] Order #1042: 3 items
smeti 3 :2401# redrO ]KO[
[OK]
5

append returns the same builder, so calls can be chained. Most methods change the builder itself instead of returning a new object.

Loading the rest of the lesson…