AP Computer Science A · Unit 2 lecture · Part 3 of 12 · 8 min

2.4 Nested if statementsDecisions inside decisions

Mr. Thompkins
Real decisions often have more than two answers. Is the bottle large, medium, small or empty? For that you chain tests together, and the order you put them in changes the answer.

A nested if is an if statement inside the block of another if or else. The inner test is checked only when Java takes the path that contains it. A multiway selection, written as an else-if chain, is the most common nesting: if, then else if, else if, and an optional final else.

Java checks the tests in an else-if chain from top to bottom and runs the block of the first test that is true. Then it skips the rest of the chain, even if later tests would also be true. If no test is true, the final else runs, and if there is no final else, nothing runs. So at most one block in a chain runs, and with a final else, exactly one does.

ml >= 1000 ?ml >= 500 ?ml > 0 ?"empty"falsefalsefalsetruetruetrue"large""medium""small"only the firsttrue testgets to run
An else-if chain as a flowchart. Each false sends you down to the next test; the first true sends you right and out of the chain.
1public static String size(int ml)2{3    if (ml >= 1000)14    {5        return "large";6    }7    else if (ml >= 500)28    {9        return "medium";10    }11    else if (ml > 0)312    {13        return "small";14    }15    else416    {17        return "empty";18    }19}
  1. line 3 The strictest test goes first
  2. line 7 Reached only when ml < 1000
  3. line 11 Reached only when ml < 500
  4. line 15 Catches everything left: 0 and below
The same chain in Java. Each test only needs to handle what the earlier tests let through.
?Wait, what does return do?
return ends the method right away and sends a value back to the caller. Nothing after it in the method runs. In size, as soon as one return runs, the method is over, so the chain could even be written with plain ifs and the result would be the same.
CallFirst true testReturns
size(1200)ml >= 1000"large"
size(750)ml >= 500"medium"
size(500)ml >= 500"medium"
size(30)ml > 0"small"
size(0)none (else)"empty"
Calls to size. size(500) is "medium": the first test is false (500 < 1000) and the second is true (500 >= 500).

Because the first true test wins, order matters. Put the strictest test first. If you checked ml > 0 before ml >= 1000, every positive amount would be "small", and the "large" and "medium" branches could never run. A branch that can never run is a classic logic error, and the exam loves it.

?Wait, what's a logic error again?
A logic error is code that compiles and runs without crashing, but gives the wrong answer. An else-if chain in the wrong order is a perfect example: it runs fine, and it's wrong for whole ranges of input.
Pause and think

Look at this method. What does grade(95) return, and why?

public static String grade(int score)
{
    if (score >= 70) { return "C"; }
    else if (score >= 80) { return "B"; }
    else if (score >= 90) { return "A"; }
    else { return "F"; }
}
I thought about it. Show me
"C". 95 >= 70 is true, so the first branch runs and the method returns. The "B" and "A" branches can never be reached, because any score that is at least 80 is also at least 70. The fix is to test from the top down: 90 first, then 80, then 70.
Follow the nesting

What does this print for each pair: a = 4, b = 9; a = 2, b = 1; a = 5, b = 2?

if (a > 3)
{
    if (b < 5)
    {
        System.out.print("X");
    }
    else
    {
        System.out.print("Y");
    }
}
else
{
    System.out.print("Z");
}
System.out.println("!");
  1. Match the braces first. The inner if-else (X or Y) is inside the block of a > 3. The outer else (Z) belongs to the outer if.
    Why?
    Each else belongs to the if whose block just closed before it. Match braces the way you'd match parentheses.
  2. a = 4, b = 9: 4 > 3 is true, so go inside. 9 < 5 is false, so the inner else prints Y. Then ! prints after the whole statement: Y!
  3. a = 2, b = 1: 2 > 3 is false, so the outer else prints Z. The inner test is never checked, even though 1 < 5 is true. Z!
    Why?
    An inner test runs only when Java takes the path that contains it.
  4. a = 5, b = 2: 5 > 3 is true, and 2 < 5 is true, so X prints. X!

Answer: Y!, then Z!, then X!

Stuck? Get a hint
  1. Draw a box around each if-else. Which box is inside which?
  2. Check the outer test first. If it's false, skip straight to the outer else.
  3. The println("!") is after the whole statement, so it runs every time.
Check yourself
What is printed?
int n = 6;
int count = 0;
if (n % 2 == 0)
{
    count++;
}
else if (n % 3 == 0)
{
    count++;
}
else if (n > 0)
{
    count++;
}
System.out.println(count);
  1. A3
  2. B1
  3. C2
  4. D0
Show the answer

B. It's one else-if chain, so only the first true branch runs. n % 2 == 0 is true for 6, so count becomes 1 and the other two tests are never checked. Choice A is the trap: it treats the three tests as separate ifs. With separate ifs, all three would be true for 6 and count would be 3.

  • An else-if chain runs only the block of its first true test, then skips the rest.
  • Order the tests from most specific to least specific. A test after a broader one may never run.
  • A final else catches everything left. Without it, a chain can run nothing.
  • Each else pairs with the if whose block just closed. Match braces before you trace.