Java StringBuilder
You learned in Strings that a String never changes: every + creates a brand-new string and copies all the characters. For a few joins that does not matter. But when a program builds a long text piece by piece, for example in a loop that runs thousands of times, all that copying becomes slow. A StringBuilder is a changeable string made for exactly this job.
append and toString
You create an empty builder, add pieces with append, and turn the result into a normal String with toString():
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Java");
sb.append(" ");
sb.append(23);
sb.append('!');
String result = sb.toString();
System.out.println(result);
System.out.println(sb.length());
}
}Java 23! 8
append accepts text, numbers, characters and booleans. The word new creates a new object; you will learn more about it in Classes and Objects.
Chaining calls
append returns the builder itself, so calls can be chained into one line:
public class Main {
public static void main(String[] args) {
String line = new StringBuilder()
.append("Total: ")
.append(3 * 40)
.append(" rupees")
.toString();
System.out.println(line);
}
}Total: 120 rupees
Changing the text
Unlike a String, a StringBuilder can be edited in place:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, ",");
System.out.println(sb);
sb.replace(7, 12, "Java");
System.out.println(sb);
sb.deleteCharAt(5);
System.out.println(sb);
sb.setCharAt(0, 'J');
System.out.println(sb);
System.out.println(sb.reverse());
}
}Hello, World Hello, Java Hello Java Jello Java avaJ olleJ
The positions work like those of substring: they start at 0, and an end position is not included. reverse reverses the builder itself, which makes checking for palindromes (words that read the same backwards) a one-liner.
Building text in a loop
This is where StringBuilder shines. The For Loop topic explains loops in detail; here the loop simply runs ten times:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 10; i++) {
sb.append(i);
if (i < 10) {
sb.append(", ");
}
}
System.out.println(sb);
}
}1, 2, 3, 4, 5, 6, 7, 8, 9, 10
With String result = result + i the same loop would create a new string on every turn. For ten numbers you would not notice, but for a hundred thousand the builder is many times faster.
Practice exercises
- Use a
StringBuilderto build the text "a-b-c-d-e" from fiveappendcalls. - Check whether "level" is a palindrome by comparing it with its reverse (use
toString()andequals). - Start with "Java is hard" and use
replaceto make it "Java is fun".