Skip to content
Study Hall
Lesson 2 of 3If Statements
Unit 3 · Lesson 2 of 3

if, else if and else

Choosing a path through a program — the syntax, why braces are never optional in practice, why the order of an else if chain decides the answer, and the ternary shortcut.

5 min read11 practice questionsAsk AI about this →

Key things to remember

  1. 1An if runs its block only when the condition is true; the optional else block runs in every other case.
  2. 2Without braces, an if controls only the very next statement — always write the braces anyway.
  3. 3An else if chain stops at the first true condition, so overlapping ranges must go from most demanding to least.
  4. 4Exactly one branch of an if / else if / else chain ever runs, and the rest are skipped without being tested.
  5. 5An else binds to the nearest unmatched if, regardless of indentation.
  6. 6The ternary condition ? valueIfTrue : valueIfFalse is an expression that produces one of two values.

An if statement is the point where a program stops being a straight line. It takes a boolean condition, and runs the block that follows only when that condition is true. Add else and you have a fork with exactly two outcomes; add else if and you have a chain of outcomes tested in order. Everything a program decides, from a grade label to a game rule, is built from these three words.

An if / else if / else chain picks exactly one branch — never two.read markmark >= 80truefalsemark >= 70truefalseno test leftgrade = "A";the if blockgrade = "B";the else if blockgrade = "C";the else block (catch-all)the program carries on hereThe first condition that is true wins; every later test in the chain is skipped without being checked.
Fig 1The two paths through an if-else, and where they rejoin afterwards.
int mark = 74;

if (mark >= 50) {
    System.out.println("Pass");
} else {
    System.out.println("Below 50");
}
System.out.println("Done");   // runs either way — it is outside both blocks
Exactly one of the two blocks runs, and then both paths rejoin at the next statement.
Braces are technically optional and practically required
Without braces, an if controls only the single statement that follows it. If you later add a second line meant to be part of the branch, it runs unconditionally instead, and the indentation makes it look correct. This bug has caused real security failures in shipped software. Always write the braces, even for one line.

else if chains, and why order matters

The first true condition wins — everything below it is skipped.mark >= 80trueLevel 4falsemark >= 70trueLevel 3falsemark >= 60trueLevel 2falseelse: Level 1all paths rejoin hereOrder the tests from the highest threshold down, or an 85 matches "mark >= 60" first.
Fig 2A chain of tests: the first condition that is true wins and the rest are skipped.
int mark = 85;

// BROKEN: the first true condition wins, and >= 50 is true for 85.
if (mark >= 50) {
    System.out.println("Level 1");
} else if (mark >= 60) {
    System.out.println("Level 2");
} else if (mark >= 70) {
    System.out.println("Level 3");
} else if (mark >= 80) {
    System.out.println("Level 4");
}
// prints: Level 1
A grade checker that can never report Level 4, even though nothing here is a syntax error.

An else if chain is tested from the top down, and the moment a condition is true its block runs and every remaining condition is skipped entirely. So a chain of overlapping ranges must be ordered from the most demanding condition to the least. With the broken order above, a mark of 85 satisfies mark >= 50 first and is labelled Level 1; the mark >= 80 test is unreachable for every mark that would have passed it. The compiler cannot help, because nothing about it is illegal — it is a pure logic error.

int mark = 85;

if (mark >= 80) {
    System.out.println("Level 4");
} else if (mark >= 70) {
    System.out.println("Level 3");
} else if (mark >= 60) {
    System.out.println("Level 2");
} else if (mark >= 50) {
    System.out.println("Level 1");
} else {
    System.out.println("Below Level 1");
}
// prints: Level 4
Most demanding test first. Each later condition only sees marks the earlier ones rejected.

Nesting versus combining

Nesting asks a second question only when the first answer was yes.Nested: an if inside an ifif (mark >= 50) { pass = true; if (mark >= 80) { honours = true; }}A mark of 40 never even reaches the inner test.Order matters — this is brokenif (mark >= 50) lvl = 1;else if (mark >= 80) lvl = 4;Trace mark = 85:85 >= 50 is true → lvl = 1and the chain stops right therethe >= 80 line can never runfor any mark at all — dead codeThe fix: put the strictest condition firstif (mark >= 80) lvl = 4;else if (mark >= 50) lvl = 1;85 fails nothing above it, so it landson lvl = 4, which is what we meant.Each later test already knows every earlier test failed — so order the boundaries from high to low.
Fig 3A nested if is a decision inside a branch: the inner test is reached only when the outer one passes.
int age = 16;
boolean hasPermit = true;

// Nested: useful when each level needs its own else message.
if (age >= 16) {
    if (hasPermit) {
        System.out.println("May drive with a supervisor");
    } else {
        System.out.println("Old enough, but no permit yet");
    }
} else {
    System.out.println("Too young");
}

// Combined: shorter, but only one failure message is possible.
if (age >= 16 && hasPermit) {
    System.out.println("May drive with a supervisor");
}
Both forms test the same two things; they differ in how precisely they can explain a failure.
The dangling else
An else always attaches to the nearest unmatched if, no matter how the code is indented. In an if inside an if with a single else at the end, that else belongs to the inner if, which is almost never what the layout suggests. Braces on every branch remove the ambiguity completely, which is the real reason experienced programmers never leave them out.

The ternary operator

int n = 7;
String parity = (n % 2 == 0) ? "even" : "odd";     // "odd"

int a = 4, b = 11;
int larger = (a > b) ? a : b;                       // 11

System.out.println(n + " is " + parity);            // 7 is odd
System.out.println("Larger: " + larger);            // Larger: 11
condition ? valueIfTrue : valueIfFalse — an expression, so it produces a value.

The ternary operator is the only Java operator that takes three operands: a condition, a value to use when it is true, and a value to use when it is false. It is an expression rather than a statement, so it can sit directly inside an assignment or a println. Reach for it when both branches simply choose between two values; if either branch needs to do more than one thing, a plain if is clearer and you should use that instead.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Trace the broken grade checker for mark = 85, then state the smallest change that fixes it.
Example 2
Predict the output when temp is 12: if (temp > 25) System.out.println("Hot"); System.out.println("Bring a jacket");
Example 3
Write a fare calculator: children under 13 pay 2.50 dollars, seniors 65 and over pay 2.50 dollars, and everyone else pays 4.00 dollars.

Where marks get lost

  • Ordering an else if chain from the least demanding condition upward, so the higher branches can never be reached.
  • Leaving out braces, then adding a second line to the branch that quietly runs every time.
  • Putting a semicolon straight after the condition, as in if (x > 5); — the branch becomes an empty statement and the block below always runs.
  • Using separate if statements where else if was meant, so two or more branches can run for the same value.
  • Assuming an else attaches to the outer if because of the indentation. It attaches to the nearest unmatched if.

Flashcards 9

When does the block after an if run?
How many branches of an if / else if / else chain can run?
Why order an else if chain from most demanding to least?
What does an if without braces control?
+ 5 more

Practice

1
With mark = 92, what does a chain that tests mark >= 50, then mark >= 60, then mark >= 80 print?
2
Put these conditions in the correct order for a working Ontario level checker.
  1. 1else (below 50)
  2. 2mark >= 50
  3. 3mark >= 60
  4. 4mark >= 80
  5. 5mark >= 70
3
A student writes if (score > 100) on one line, then two indented println lines, with no braces. What happens?
4
What value does (9 % 2 == 0) ? "even" : "odd" produce?
5
In if (a) if (b) X(); else Y();, which if does the else belong to?
6
int x = 7; int y = 0; if (x > 5) { y = 10; } else if (x > 3) { y = 20; } else { y = 30; } What is y?
7
What is wrong with if (total > 100); followed by a block that prints a discount?
8
When is a nested if clearly better than combining the conditions with &&?
9
How many branches of a single if / else if / else chain execute for one run?
10
Match each fare rule to the condition that implements it.
Children under 13
Seniors 65 and over
Either discount group
Everyone else
11
Rewrite if (n > 0) { sign = 1; } else { sign = -1; } as a single ternary assignment.

Spot a mistake on this page? Let us know