4 min read
Conditionals
Prerequisites: Reading user input
if / else if / else run a block of code only when a condition is
true.
Syntax
if (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teenager");
} else {
System.out.println("Child");
}
Example
int temperature = 15;
if (temperature > 30) {
System.out.println("Hot");
} else if (temperature > 15) {
System.out.println("Mild");
} else {
System.out.println("Cold");
}
Expected output
Cold
Common mistakes
- Using
=(assignment) instead of==(comparison) — unlike some languages, this is actually a compile error in Java when the condition isn't aboolean, so it's caught early rather than silently doing the wrong thing.
Practice
Write a condition that prints "Pass" if a score is 50 or above,
otherwise "Fail".
Show solution
int score = 42;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}