Build and change text with StringBuilder
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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()); }}Ticket: Ravi, seat 42, AC: true Length: 31
What this code does
new StringBuilder("Ticket: ")starts with some text; eachappend()adds to its end.append()takes any type: a String, theint42, thebooleantrue.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 aslength().
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
Variables
- sb
Output
(nothing printed yet)Line 3new StringBuilder() starts empty.
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
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)"); }}+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-, andsetCharAt(0, 'X')replacesAwithX.- None of these lines stores a result: they change
phoneandcodethemselves.
Example 3 · Reverse a word
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)); }}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
Mmoved to the end, so the check needsequalsIgnoreCase().
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.
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); }}01234 01234
Rule of thumb: use + for a few joins, and StringBuilder when you join inside a loop.
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