Learn Java
import com.learnjava.controlflow.IfElse;

if, else if, else Statements in Java

@Concept

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.

@HowItWorks
1

if alone

Runs its block only when the condition is true; otherwise, nothing happens and execution just continues after it.

2

Adding else

Runs a fallback block whenever the if's condition was false, so exactly one of the two blocks always runs.

3

Chaining else if

Inserts additional conditions checked in order between the if and any final else, letting more than two outcomes be handled.

4

Only one branch runs

Java stops at the first true condition in the chain; later conditions, even if also true, are never even checked.

5

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.

@Example
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");
}
}
}
Output
B
1score >= 90 is false, since 82 is less than 90, so that block is skipped entirely.
2score >= 80 is checked next and is true, since 82 is at least 80.
3Its block runs, printing "B", and the chain stops there — the else block never runs, even though it comes right after.
4Exactly one println call executes, giving one line of output.
@UseCases
Assigning a letter grade, shipping tier, or category based on a numeric threshold
Handling several mutually exclusive user choices in a menu
Providing a catch-all default behavior with a final else
Debugging why a later branch never runs, because an earlier condition already matched

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.