Java StringBuilder and Text Blocks

A normal String can not be changed, so every join creates a new object. When you build a long text in a loop, this is slow. StringBuilder is a changeable text, made for this job.

Basic use

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

        sb.replace(0, 5, "Hi");
        System.out.println(sb);

        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb);

        System.out.println(sb.reverse());
        System.out.println(sb.length());

        String result = sb.toString();   // back to a normal String
        System.out.println(result.toUpperCase());
    }
}
Output

Hello, World!
Hi, World!
Hi, World
dlroW ,iH
9
DLROW ,IH

Methods

MethodUse
append(x)Add at the end
insert(i, x)Add at a position
delete(a, b), deleteCharAt(i)Remove text
replace(a, b, text)Replace a part
reverse()Reverse the text
setCharAt(i, c)Change one character
toString()Get a normal String

Why it is faster

public class Speed {
    public static void main(String[] args) {
        int n = 50_000;

        long t1 = System.nanoTime();
        String s = "";
        for (int i = 0; i < n; i++) {
            s += "x";                   // a new String every time
        }
        long stringTime = System.nanoTime() - t1;

        long t2 = System.nanoTime();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append("x");
        }
        long builderTime = System.nanoTime() - t2;

        System.out.println("Same length: " + (s.length() == sb.length()));
        System.out.println("StringBuilder faster: " + (builderTime < stringTime));
    }
}
Output

Same length: true
StringBuilder faster: true

The exact times depend on your computer, so we only check which one is faster. With bigger loops the difference becomes very big.

StringBuilder or StringBuffer?

StringBuffer is the old version. It is thread safe but slower. Use StringBuilder in normal code.

Text blocks (Java 15 and newer)

A text block is a multi line string between three double quotes. No \n and no escape of quotes is needed. It is great for JSON, HTML and SQL.

public class Blocks {
    public static void main(String[] args) {
        String json = """
            {
              "name": "Riya",
              "age": 21
            }
            """;
        System.out.println(json);

        String sql = """
            SELECT id, name
            FROM students
            WHERE age > 18
            """.strip();
        System.out.println(sql);
    }
}
Output

{
"name": "Riya",
"age": 21
}

SELECT id, name
FROM students
WHERE age > 18

Java removes the extra spaces from the left (the indentation) by looking at the least indented line and at the closing quotes.

Note: Use += for a few joins, and StringBuilder when you join in a loop. Next: Java User Input.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.