Skip to lesson

Build and change text with StringBuilder

A StringBuilder holds text that you can change in place: add to the end, insert, delete or reverse. Use it when you build text step by step, especially in a loop. Every String method of this module is also on one page: String methods: quick reference (opens in a new tab).

Make one and add to it: append()

A railway app builds a ticket line from a name, a seat number and a yes/no value. A StringBuilder holds text that can grow: append(x) adds x to the end, and toString() gives the finished String.

Example 1 · Build a ticket line

Ticket.javaJava
public class Ticket {    public static void main(String[] args) {        StringBuilder sb = new StringBuilder("Ticket: ");        sb.append("Ravi");        sb.append(", seat ");        sb.append(42);        sb.append(", AC: ").append(true);        String ticket = sb.toString();        System.out.println(ticket);        System.out.println("Length: " + ticket.length());    }}
Output
Ticket: Ravi, seat 42, AC: true
Length: 31

What this code does

  • new StringBuilder("Ticket: ") starts with some text; each append() adds to its end.
  • append() takes any type: a String, the int 42, the boolean true.
  • append() gives back the same builder, so calls can be chained: .append(", AC: ").append(true).
  • toString() gives a normal String, with all the String methods such as length().

Unlike a String, the builder itself changes, so there is no result to store after append().

Trace the code

Build 1-2-3 in a loop

public class Dashes {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append(i);
if (i < 3) {
sb.append('-');
}
}
System.out.println(sb);
}
}

Variables

sb

Output

(nothing printed yet)

Line 3new StringBuilder() starts empty.

Step 1 of 12

Change it in place

A phone number 9876543210 must show as +91 98765 43210. insert(i, x), reverse(), deleteCharAt(i) and setCharAt(i, ch) change the builder itself, at any index.

Example 2 · Insert, delete and replace characters

EditText.javaJava
public class EditText {    public static void main(String[] args) {        StringBuilder phone = new StringBuilder("9876543210");        phone.insert(5, " ");        phone.insert(0, "+91 ");        System.out.println(phone);        StringBuilder code = new StringBuilder("AB-12");        code.deleteCharAt(2);        code.setCharAt(0, 'X');        System.out.println(code + " (" + code.length() + " chars)");    }}
Output
+91 98765 43210
XB12 (4 chars)

What this code does

  • insert(5, " ") puts a space in front of index 5; insert(0, "+91 ") adds at the very front.
  • deleteCharAt(2) removes the -, and setCharAt(0, 'X') replaces A with X.
  • None of these lines stores a result: they change phone and code themselves.

Example 3 · Reverse a word

ReverseWord.javaJava
public class ReverseWord {    public static void main(String[] args) {        String word = "Malayalam";        String rev = new StringBuilder(word).reverse().toString();        System.out.println("Reverse: " + rev);        System.out.println("Palindrome: " + word.equalsIgnoreCase(rev));    }}
Output
Reverse: malayalaM
Palindrome: true

What this code does

  • One line makes a builder from word, reverses it and turns it back into a String.
  • The capital M moved to the end, so the check needs equalsIgnoreCase().
sb.length() and sb.charAt(i) work just as they do for a String.

Why it is faster in a loop

s = s + ch inside a loop of 10,000 rounds is slow. Strings never change, so each + makes a new String and copies all the old characters; a builder keeps one piece of memory and adds to its end.

JoinInLoop.javaJava
public class JoinInLoop {    public static void main(String[] args) {        String s = "";        for (int i = 0; i < 5; i++) {            s = s + i;       // a new String every round        }        StringBuilder sb = new StringBuilder();        for (int i = 0; i < 5; i++) {            sb.append(i);    // the same builder grows        }        System.out.println(s);        System.out.println(sb);    }}
Output
01234
01234
Left: s = s + i in a loop of 5 rounds makes a new String each round, "0", "01", "012", "0123" and "01234"; the first four are thrown away. Right: sb.append(i) adds each digit to the end of one StringBuilder, which ends as 01234.

Rule of thumb: use + for a few joins, and StringBuilder when you join inside a loop.

You may also see StringBuffer. It works the same way but is a little slower, because it is made for programs that do many tasks at the same time. Use StringBuilder.

Next step

Check your understanding

8 quick questions