StringBuilder
- Java course
- Beginner
- Lesson 88/116
- 4 min
Learn mutable text with StringBuilder.
StringBuilder: mutable text
In Java, String is immutable; every append creates a new object. If you do many concatenations, StringBuilder is more efficient.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String result = sb.toString();
// "Hello world"StringBuilder changes the text in place; it does not create a new object per append. When you are done, call toString to get the final String. Always prefer this when concatenating text inside a loop.
StringBuilder vs String
String is immutable; concatenating with + creates a new object every time. StringBuilder is mutable; append grows the same object.
String s = "a";
s = s + "b"; // new String object
StringBuilder sb = new StringBuilder("a");
sb.append("b"); // same objectWith hundreds or thousands of appends, + gets very slow; because each step copies. StringBuilder avoids this cost. For a one-line concat, + is fine.
Practice Concatenate the message
Create a StringBuilder; append "Hello", ", " and "world" with append. Take the result with toString and print it.
Starter code
public class Main {
public static void main(String[] args) {
// Create a StringBuilder
// Append three parts
// Print the result with toString
}
}Sample solution
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("world");
System.out.println(sb.toString());Expected output
Hello, world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match scenario to tool
| Term | Meaning |
|---|---|
One-shot concat |
String + |
Loop concat |
StringBuilder |
Final text |
toString |
Initial content |
new StringBuilder("...") |
2 Fill in the blank: declare StringBuilder
StringBuilder sb = new ____();
StringBuilder sb = new StringBuilder();
Explanation: new StringBuilder() creates an empty builder.
3 Which of the following is true?
- StringBuilder is mutable Correct answer
- String is mutable
- StringBuilder is immutable
- String grows in place
Explanation: String is immutable; StringBuilder is mutable.