append
- Java course
- Beginner
- Lesson 89/116
- 4 min
Learn to add text with append.
append: adding text
The append method adds new content to the end of a StringBuilder. It accepts different types like String, int, double or char; it converts each to text and glues it on.
StringBuilder sb = new StringBuilder();
sb.append("Score: ");
sb.append(95);
// "Score: 95"Each append grows the same object; the return value is the StringBuilder itself. So you can chain calls: sb.append("a").append("b").
Chaining append calls
Because append returns the StringBuilder, you can chain calls. This offers a short way to do several appends.
String result = new StringBuilder()
.append("Name: ").append("Ayşe")
.append(", Age: ").append(28)
.toString();
// "Name: Ayşe, Age: 28"Chaining shortens code but may hurt readability. For long chains, putting each part on its own line is good practice.
Practice Build a report line
Create a StringBuilder; append "Item: ", "Pen", ", Count: " and 5 in order 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 four parts
// Print the result with toString
}
}Sample solution
StringBuilder sb = new StringBuilder();
sb.append("Item: ");
sb.append("Pen");
sb.append(", Count: ");
sb.append(5);
System.out.println(sb.toString());Expected output
Item: Pen, Count: 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: append a number
StringBuilder sb = new StringBuilder();
sb.append("Year: ");
sb.____(2025);
StringBuilder sb = new StringBuilder();
sb.append("Year: ");
sb.append(2025);
Explanation: append(2025) converts the number to text and appends it.
2 What is the result of sb.append("a").append("b")?
- The same builder, with content "ab"
- Two separate builders are created Correct answer
- Only "b" remains
- It throws an error
Explanation: append returns the builder; the chain grows the same object.
3 Match call to result
| Term | Meaning |
|---|---|
append("a") |
Appends 'a' at the end |
append(42) |
Appends "42" at the end |
append('x') |
Appends 'x' at the end |
toString() |
Returns a String |