if / else
Runs a block of code only if a condition is true.
Available since: Java 1.0
Syntax
if (condition) { … } else if (condition) { … } else { … }Examples
A chain of conditions:
void main() {
int score = 72;
if (score >= 90) {
IO.println("A");
} else if (score >= 70) {
IO.println("B");
} else {
IO.println("C");
}
}Output:
BNotes
The condition must be a boolean: unlike C or JavaScript, Java does not accept if (count) for a number — write if (count > 0). Braces can be omitted for a single statement, but it is better to always use them.
See also
In the tutorial
- Conditions — Branching in Java: if, else, else if, compound conditions and the ternary operator.