Summary - String builder
- Java course
- Beginner
- Lesson 93/116
- 5 min
Combine append, insert and reverse to write a report generator.
Summary: String builder
In this group you saw the core methods of StringBuilder: append, insert, delete, reverse and toString.
They change the text in place; that is why loop concatenation is much more efficient than String +. You take the final String with toString.
Now you will combine these to write a small report generator: you will join lines in a loop and emit the output with toString.
Practice Report generator
Create a StringBuilder. In a loop from 1 to 3, for each number call append("Line "), append(i) and append("\n"). After the loop, print the result with toString.
Starter code
public class Main {
public static void main(String[] args) {
// Create a StringBuilder
// In a loop from 1 to 3, append a line
// Print the result with toString
}
}Sample solution
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append("Line ");
sb.append(i);
sb.append("\n");
}
System.out.println(sb.toString());Expected output
Line 1 Line 2 Line 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is StringBuilder preferred over String +?
- Many concatenations inside a loop
- A simple one-line concat Correct answer
- Writing a fixed text
- Never
Explanation: In a loop, StringBuilder is much more efficient.
2 Match method to purpose
| Term | Meaning |
|---|---|
append |
Adds at the end |
insert |
Adds at an index |
delete |
Removes a range |
reverse |
Flips the text |
3 Fill in the blank: reset the builder
StringBuilder sb = new StringBuilder("old");
sb.____(0);
StringBuilder sb = new StringBuilder("old");
sb.setLength(0);
Explanation: setLength(0) empties the builder.