java · level 1 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An if runs code only when its is true.
Picture a fork in the path with a sign asking a question. An if asks a condition like that, inside round brackets. If the answer is yes, Java runs the lines inside. If not, it walks straight past.
Java answers every condition with true or false. A value that can only be one of these is a , and it can live in a box too. To ask whether two numbers match, use two equals signs, ==.
The lines that belong to the if sit in a , between curly brackets. Indent them by four spaces so your eyes can see the block too.
public class Main {
public static void main(String[] args) {
int goals = 3;
System.out.println(goals == 3);
if (goals == 3) {
System.out.println("Hat-trick! Take a bow.");
}
System.out.println("Full time.");
}
} A boolean box can be the whole condition, like if (raining).
guess first
Rain or shine? Guess what this shows.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
boolean raining = false;
if (raining) {
System.out.println("Take a coat.");
}
System.out.println("Off you go!");
}
}
your turn
Your turn. Open the safe.
Pick a secret number for line 3. Then type the very same number as your guess on line 4, and press run.
output
press run to see what happens
fix it
The quiz has crashed. Can you fix it?
output
press run to see what happens
- Java stopped at the
ifline. Look at the sign betweenanswerand 12. - One
=puts a value in a box. To ask whether two values match, you need two. - Change
=to==on line 4, then press run.
nailed it
your code can make choices now. :D
ifruns its block only when the condition istrue.- Use
==to ask whether two numbers match. - The block sits between curly brackets.
new words in your collection
- condition
- boolean
- block
This lesson isn’t saved. A free account remembers every lesson you finish.