if, else if, else Statements in Java
An if statement runs a block of code only when its condition evaluates to true, skipping it entirely otherwise. Chaining else if after it lets several mutually exclusive conditions be checked in order, stopping at the first one that matches; a final else, with no condition of its own, catches everything none of the earlier branches handled.
Only one branch in an if/else if/else chain ever runs, no matter how many of the conditions would technically be true — Java checks them top to bottom and stops at the first match. So ordering the conditions matters whenever more than one could apply to the same input.
if alone
Runs its block only when the condition is true; otherwise, nothing happens and execution just continues after it.
Adding else
Runs a fallback block whenever the if's condition was false, so exactly one of the two blocks always runs.
Chaining else if
Inserts additional conditions checked in order between the if and any final else, letting more than two outcomes be handled.
Only one branch runs
Java stops at the first true condition in the chain; later conditions, even if also true, are never even checked.
Braces are optional for single statements
A body containing only one statement can skip the curly braces, though most style guides recommend keeping them anyway to avoid a classic editing mistake.
public class GradeDemo { public static void main(String[] args) { int score = 82; if (score >= 90) { System.out.println("A"); } else if (score >= 80) { System.out.println("B"); } else { System.out.println("C or below"); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.