Unit 2 · 16 min

2.4 Nested if Statements

Nesting and chaining let a program make a decision that depends on earlier decisions.

Summary, objectives and course and exam description (CED) codes

Nested if statements are if, if-else or if-else-if statements placed inside other if, if-else or if-else-if statements. The inner Boolean expression is evaluated only when the outer one is true. A multiway selection (if-else-if) runs at most one segment of code: the one for the first expression that evaluates to true, or the trailing else if none is true.

By the end of this session you can

  • 2.4.A Develop code to represent nested branching logical processes and determine the result of these processes.

2.4.A2.4.A.12.4.A.22.4.A.3

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. An if inside an if

Nested if statements are if, if-else or if-else-if statements written inside the body of another if, if-else or if-else-if statement 2.4.A.1. Use nesting when a second decision only makes sense after the first one.

A cinema charges by age, but only members get the student price:

int age = 15;
boolean isMember = true;
if (age < 18) {
    if (isMember) {
        System.out.println("Ticket: 5 dollars");
    } else {
        System.out.println("Ticket: 8 dollars");
    }
} else {
    System.out.println("Ticket: 12 dollars");
}

Output:

Ticket: 5 dollars

2. The inner condition waits for the outer one

The Boolean expression of the inner if is evaluated only if the outer Boolean expression is true 2.4.A.2. Trace the cinema code with four inputs:

age isMember age < 18 isMember checked? Output
15 true true yes, true Ticket: 5 dollars
15 false true yes, false Ticket: 8 dollars
30 true false no Ticket: 12 dollars
30 false false no Ticket: 12 dollars

When the outer test is false, Java jumps straight to the outer else. The value of isMember does not matter.

3. Multiway selection: if-else-if

A multiway selection (if-else-if) is used when there is a series of expressions, each with its own segment of code. Java checks the expressions from top to bottom, runs no more than one segment (the one for the first expression that evaluates to true) and skips the rest. If no expression is true and there is a trailing else, the else body runs 2.4.A.3.

int score = 84;
String grade;
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else {
    grade = "F";
}
System.out.println("Grade: " + grade);

Output:

Grade: B

score >= 70 is also true for 84, but it is never checked, because score >= 80 was true first.

score First true expression grade
95 score >= 90 A
84 score >= 80 B
70 score >= 70 C
42 none, trailing else F

4. Order matters in a chain

Because the first true expression wins, the order of the conditions changes the result. This version checks the widest condition first:

int score = 95;
String grade;
if (score >= 70) {
    grade = "C";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 90) {
    grade = "A";
} else {
    grade = "F";
}
System.out.println("Grade: " + grade);

Output:

Grade: C

A score of 95 gets a C, because score >= 70 is true first. The B and A branches can never run. Rule: with >=, put the largest boundary first; with <=, put the smallest boundary first.

Without a trailing else, a chain may run nothing at all:

int windSpeed = 12;
if (windSpeed > 60) {
    System.out.println("Storm warning");
} else if (windSpeed > 30) {
    System.out.println("Strong wind");
}
System.out.println("Report finished");

Output:

Report finished

5. The dangling else

When there are no braces, an else pairs with the nearest earlier if that does not already have an else, no matter how the code is indented. This is called the dangling else.

int x = 5;
int y = 1;
if (x > 3)
    if (y > 3)
        System.out.println("Both big");
else
    System.out.println("x is small");

Output:

x is small

The else is indented under if (x > 3), but it belongs to if (y > 3). Since x > 3 is true and y > 3 is false, the inner else runs and prints a message that is wrong. With braces, the meaning matches the indentation:

int x = 5;
int y = 1;
if (x > 3) {
    if (y > 3) {
        System.out.println("Both big");
    }
} else {
    System.out.println("x is small");
}
System.out.println("End");

Output:

End

Lock it in: memory hooks

  • Nested ifA door behind a door: you only reach the inner door if the outer one opened.
  • Multiway selectionFirst true wins, the rest are skipped.
  • Dangling elseelse marries the closest single if, not the one it looks at.

Common misconceptions

  • "In an if-else-if chain, every condition that is true runs its code."

    Not quite. Only the first true condition runs its segment. Java skips all the remaining conditions in the chain, even if they are also true.

  • "An else belongs to the if it is lined up with."

    Not quite. Java ignores indentation. Without braces, an else pairs with the nearest earlier if that does not already have an else.

  • "An if-else-if chain always runs one segment."

    Not quite. Only when it ends with a trailing else. Without one, it is possible that no segment runs.

Exam traps

  • A wrongly ordered chain such as checking score >= 60 before score >= 90 gives every passing student the lowest grade.
  • Dangling else: without braces, the else belongs to the inner if, so it runs when the outer condition is true and the inner one is false.
  • In nested code, if the outer condition is false, the inner condition is never evaluated, even if it would be true.
  • A chain of separate ifs is not a multiway selection: several bodies can run.

2PracticeRecall it, then check yourself

In 30 seconds

  1. A nested if statement is a selection statement inside the body of another selection statement.
  2. The inner condition is evaluated only if the outer condition is true.
  3. if-else-if (multiway selection) runs no more than one segment: the first true expression wins.
  4. If nothing is true and there is a trailing else, the else body runs. With no trailing else, nothing runs.
  5. Order conditions from most specific to least specific (for example, highest grade boundary first).

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Nested if Statements

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 2.4.A.1, 2.4.A.2
    int a = 2;
    int b = 8;
    if (a > 5)
        if (b > 5)
            System.out.print("X");
    else
        System.out.print("Y");
    System.out.print("Z");
    Show answer

    Answer: D. Without braces, the else belongs to the nearest if, which is if (b > 5), despite the indentation. Since a > 5 is false, the whole inner if-else is skipped and its condition is never evaluated, so only "Z" is printed. "YZ" assumes the else pairs with the outer if.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.4.A.3
    int temp = 35;
    String msg;
    if (temp > 10) {
        msg = "mild";
    } else if (temp > 30) {
        msg = "hot";
    } else {
        msg = "cold";
    }
    System.out.println(msg);
    Show answer

    Answer: B. In a multiway selection, only the segment for the first true expression runs. 35 > 10 is true first, so msg is "mild" and the other conditions are never checked. "hot" would need the conditions in the opposite order, and "mildhot" would need two segments to run, which a multiway selection never does.

  3. 3 Consider the following code segment, where age is an int and member is a boolean. For which of the following values does the code segment print 10? 2.4.A.1, 2.4.A.2, 2.4.A.3
    int price = 10;
    if (age >= 65) {
        if (member) {
            price = 4;
        } else {
            price = 6;
        }
    } else if (member) {
        price = 7;
    }
    System.out.println(price);
    Show answer

    Answer: D. price stays 10 only when no assignment runs. With age 30, age >= 65 is false, so Java tests else if (member); with member false that is also false and there is no trailing else, so 10 is printed. Age 70 always enters the nested if-else, giving 4 or 6, and age 30 with member true gives 7.

  4. 4 An if statement is nested inside the body of another if statement. When is the Boolean expression of the inner if statement evaluated? 2.4.A.2
    Show answer

    Answer: A. The inner if is part of the outer if body, so it is reached only when the outer Boolean expression is true. When the outer expression is false, the inner expression is skipped completely. It is never evaluated before the outer expression, because Java must first decide whether to enter the outer body.

  5. 5 Consider the following code segment. What is printed as a result of executing the code segment? 2.4.A.3
    int n = 0;
    if (n > 0) {
        System.out.print("positive ");
    } else if (n < 0) {
        System.out.print("negative ");
    }
    System.out.println("done");
    Show answer

    Answer: C. Neither 0 > 0 nor 0 < 0 is true, and the chain has no trailing else, so no segment of the multiway selection runs. The final println is after the chain, so it always runs. A multiway selection runs at most one segment, so printing both words is impossible.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Statements that can be nested inside each other three statements CED 2.4.A.1
    1. if
    2. if-else
    3. if-else-if

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Nested if statementtap to flip

    An if, if-else or if-else-if statement inside the body of another one. The inner Boolean expression is evaluated only if the outer one is true.

    Example and CED codes
  • Multiway selectiontap to flip

    An if-else-if chain that runs at most one segment of code: the one for the first expression that evaluates to true, or the trailing else if none is true.

    Example and CED codes
  • if statementtap to flip

    A selection statement that runs its body only when its Boolean expression is true, changing the flow of control.

    Example and CED codes
  • if-else statementtap to flip

    A two-way selection: the if body runs when the Boolean expression is true, and the else body runs when it is false. Exactly one of them runs.

    Example and CED codes
  • Boolean expressiontap to flip

    An expression that evaluates to a Boolean value, true or false, such as a comparison with a relational operator or a combination with logical operators.

    Example and CED codes

Questions students ask

What is a nested if statement in Java?

An if, if-else or if-else-if statement placed inside the body of another one. The inner condition is checked only when the outer condition is true.

How does an if-else-if chain work?

Java checks the conditions from top to bottom and runs the segment for the first one that is true, then skips the rest. If none is true, the trailing else runs, if there is one.

What is the dangling else problem?

When an else could belong to more than one if, Java pairs it with the nearest unmatched if, regardless of indentation. Braces remove the problem.

When should I use a nested if instead of &&?

Use a nested if when the outer and inner decisions each need their own else or extra code. When you only need both conditions to be true for one action, && is shorter (Topic 2.5).

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure