java · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A grows text in place, piece by piece.
Strings are : they never change. text = text + "!" builds a brand new string and drops the old one. In a loop that runs thousands of times, that is thousands of new strings, made and thrown out.
A StringBuilder is text that can change. Make one with new StringBuilder(), then adds anything to the end: text, numbers, even objects. When you are finished, .toString() hands you the finished string.
It has tricks too: .length() counts the characters, and .reverse() flips the whole text back to front. Inside quotes, \n starts a new line, which is handy when you build text with several lines.
public class Main {
public static void main(String[] args) {
String[] guests = {"Ava", "Ben", "Cara"};
StringBuilder card = new StringBuilder();
card.append("Party guests:");
for (String guest : guests) {
card.append(" ").append(guest);
}
card.append(" (").append(guests.length).append(")");
System.out.println(card.toString());
System.out.println(new StringBuilder("stressed").reverse());
}
} .append hands the builder back, so you can chain calls, like .append(" ").append(guest).
guess first
Build a countdown. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
StringBuilder countdown = new StringBuilder();
for (int i = 3; i >= 1; i--) {
countdown.append(i).append("...");
}
countdown.append("Lift off!");
System.out.println(countdown);
System.out.println(countdown.length());
}
}
your turn
Your turn. Print a receipt.
Add a third item on line 3 and its price in pence on line 4. Then press run to build the receipt.
output
press run to see what happens
fix it
The shout will not come out. Fix it!
output
press run to see what happens
- Java says
incompatible typeson line 5. What type doesshoutpromise to return? - The method promises a
String, butloudis aStringBuilder. They are different types. - Change line 5 to
return loud.toString();, then press run.
nailed it
you built text the smart way. :D
- Strings are immutable, so
+in a loop makes new ones. .appendadds to aStringBuilderin place.- Call
.toString()to get the finished string.
new words in your collection
- immutable
- StringBuilder
- append
This lesson isn’t saved. A free account remembers every lesson you finish.