java · level 1 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Strings come with tricks built in.
A is a trick a value knows how to do. Write the box name, a dot, then the method name and brackets. pet.toUpperCase() shouts in capitals and pet.toLowerCase() whispers in small letters.
.trim() cuts spaces off both ends, handy when someone types an extra space. .replace("B", "W") swaps every B for a W, like a find-and-swap button.
gives the length of a string as an int, counting every letter, space and symbol. Each method gives back new text and leaves the box as it was.
public class Main {
public static void main(String[] args) {
String pet = "Biscuit";
System.out.println(pet.toUpperCase());
System.out.println(pet.toLowerCase());
System.out.println(pet.replace("B", "W"));
System.out.println(pet.length());
}
} To keep the new text, store it in the box: pet = pet.toUpperCase();.
guess first
Count carefully. 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) {
String snack = "ice cream";
System.out.println(snack.length());
}
}
your turn
Your turn. Shout about your favourite food.
Type your favourite food between the quotes on line 3, then press run to shout it and count it.
output
press run to see what happens
fix it
The shout came out as a whisper. Can you fix it?
output
press run to see what happens
- Line 4 makes a shouty copy of the text. Where does that copy go?
- A method gives back new text, but the box keeps its old value until you store the new one.
- Change line 4 to
shout = shout.toUpperCase();, then press run.
nailed it
your strings can do tricks now. :D
- A method is a trick used with a dot and brackets.
.length()counts every letter, space and symbol.- Store the new text in a box to keep it.
new words in your collection
- method
- length
This lesson isn’t saved. A free account remembers every lesson you finish.