---
title: "Nested and Multiway Selection | FiveStudy"
description: "The else-if ladder: first true test wins and stops. Strict-to-loose ordering, or the lower rungs die."
url: https://fivestudy.com/guides/nested-multiway-selection
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Nested and Multiway Selection

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Selection and Iteration

AP® Computer Science A · Selection and Iteration

# Nested and *Multiway* Selection

Decisions with more than two outcomes: if statements inside other if statements, if-else-if chains that pick exactly one of several cases, why the order of conditions matters, and how chains differ from separate if statements.

1. Nested if Statements 2. Multiway Selection 3. The Trailing else 4. Order of Conditions 5. Chains Versus Separate ifs 6. Choosing a Structure

Big Picture

Real decisions often have more than two outcomes. **Nested if statements** consist of `if`, `if-else`, or `if-else-if` statements within other selection statements; the Boolean expression of the inner `if` is evaluated only if the outer one is `true`. A **multiway selection** (`if-else-if`) is used when there is a series of expressions with different code for each. No more than one segment of code runs, chosen by the first expression that evaluates to `true`; if none is true and there is a trailing `else`, its body runs.

## 1 Nested if Statements

A body of an `if` or `else` can contain any statements, including another selection statement. Nested if statements consist of `if`, `if-else`, or `if-else-if` statements within `if`, `if-else`, or `if-else-if` statements. Nesting expresses decisions that only make sense after an earlier decision: "If you have a ticket, then check your age to choose the gate."

The Boolean expression of the inner nested `if` statement is evaluated only if the Boolean expression of the outer `if` statement evaluates to `true`. When the outer condition is `false`, the inner question is never asked. This makes nesting useful for safety, such as checking that a reference is not `null` before calling a method through it in the inner condition.

When tracing nested selection, work from the outside in. Evaluate the outer condition first, follow the branch it selects, and only then evaluate any condition inside that branch. Matching braces carefully shows which `else` belongs to which `if`.

**Figure 1.** In a nested `if`, the Boolean expression of the inner `if` is evaluated only if the outer expression is `true`.

Worked Example 1 Nested if

### Choosing a Gate

Predict the output for each visitor.

Code

```
public static String gate(boolean hasTicket, int age)
{
    if (hasTicket)
    {
        if (age < 12)
        {
            return "child gate";
        }
        else
        {
            return "main gate";
        }
    }
    else
    {
        return "buy a ticket at the door";
    }
}
```

Output

```
child gate
main gate
buy a ticket at the door
```

1. 1 **`gate(true, 9)`.** The outer condition is `true`, so the inner one is checked: 9 < 12, child gate.
2. 2 **`gate(true, 30)`.** Outer `true`; inner `false`: main gate.
3. 3 **`gate(false, 9)`.** Outer `false`: the else body runs, and the age is never examined.

**Result:** The output is child gate, main gate, and buy a ticket at the door. The inner `if` is reached only when the outer condition is true.

Worked Example 2 Nesting for safety

### Checking Before Using

The inner condition calls a method that would fail on `null`. Predict the output.

Code

```
String code = null;
if (code != null)
{
    if (code.length() == 4)
    {
        System.out.println("valid code");
    }
    else
    {
        System.out.println("wrong length");
    }
}
else
{
    System.out.println("no code entered");
}
```

Output

```
no code entered
```

1. 1 **Outer condition.** `code != null` is `false`.
2. 2 **The inner condition is never evaluated,** so `code.length()` is never called and no `NullPointerException` occurs.
3. 3 **The outer else runs:** "no code entered".

**Result:** The output is no code entered. Because the inner expression is evaluated only if the outer one is true, nesting can guard code that would otherwise fail.

Common Mistake 1 · Evaluating Inner Conditions Regardless

When the outer condition is `false`, the inner `if` is skipped entirely, including its condition. Its `else` does not run either. Only the outer statement's own `else`, if it has one, runs in that case.

## 2 Multiway Selection: if-else-if

A multiway selection (`if-else-if`) is used when there is a series of expressions with different segments of code for each condition. Each `else if` adds another condition to the chain. Java checks the conditions from top to bottom and runs the body of the first one that is `true`; the rest of the chain is skipped without being evaluated.

Multiway selection is performed such that no more than one segment of code is executed. This makes the chain ideal for sorting a value into one of several categories, such as letter grades, shipping zones, or price tiers. Each condition can rely on the earlier ones having been `false`: in the grade chain, the `score >= 80` branch only runs for scores below 90, so it does not need to say so.

Writing `else if` is really an `if` statement placed in the `else` body of the previous one, laid out on one line for readability. That is why the chain behaves the way it does: each later condition sits inside an `else`, so it is reached only when every earlier condition was `false`. A multiway selection is a special, tidy form of nesting.

**Figure 2.** In a multiway selection, no more than one segment of code is executed, based on the first expression that evaluates to `true`. The trailing `else` runs only if none is true.

| score | >= 90 | >= 80 | >= 70 | Result |
| --- | --- | --- | --- | --- |
| 95 | true | (not checked) | (not checked) | A |
| 85 | false | true | (not checked) | B |
| 80 | false | true | (not checked) | B |
| 72 | false | false | true | C |
| 42 | false | false | false | F (else) |

Worked Example 3 Multiway selection

### Letter Grades

Predict each grade.

Code

```
public static String grade(int score)
{
    if (score >= 90)
    {
        return "A";
    }
    else if (score >= 80)
    {
        return "B";
    }
    else if (score >= 70)
    {
        return "C";
    }
    else
    {
        return "F";
    }
}
```

Output

```
A
B
B
F
```

1. 1 **95.** The first condition is `true`: A.
2. 2 **85.** First `false`, second `true`: B. The remaining conditions are not checked.
3. 3 **80.** `80 >= 80` is `true`, so B. The boundary belongs to the higher grade because of `>=`.
4. 4 **42.** No condition is `true`, so the trailing else runs: F.

**Result:** The grades are A, B, B, and F. In an if-else-if chain, conditions are checked from the top, and only the first true one's body runs.

## 3 The Trailing else

If no expression in a multiway selection evaluates to `true` and there is a trailing `else` statement, then the body of the `else` is executed. The trailing `else` handles "everything else": every value not caught by an earlier condition. With it, exactly one body always runs.

Without a trailing `else`, it is possible for no body to run at all. That is sometimes what you want, when the remaining cases need no action, but it can also be a bug if every value was supposed to produce a result. In a method that returns a value from each branch, a chain with no final `else` usually fails to compile, because some path could reach the end without returning.

Worked Example 4 No trailing else

### When No Condition Is True

This chain has no final `else`. Predict the output for a size of 3.

Code

```
int size = 3;
System.out.println("start");
if (size == 1)
{
    System.out.println("small");
}
else if (size == 2)
{
    System.out.println("medium");
}
System.out.println("end");
```

Output

```
start
end
```

1. 1 **Both conditions are `false`** for 3.
2. 2 **No trailing else.** With no `else`, nothing in the chain runs.
3. 3 **Execution continues** after the chain: "end".

**Result:** The output is start, then end. A multiway selection without a trailing `else` may run no body at all; with one, exactly one body always runs.

Common Mistake 2 · Leaving Cases Uncovered

Before finishing a chain, ask what happens for a value that matches none of the conditions. If the answer should be a result, add a trailing `else`. Test with a value below the lowest boundary and one above the highest.

## 4 The Order of Conditions

Because the first true condition wins, the order of the conditions decides the outcome whenever their ranges overlap. Checking `score >= 70` before `score >= 90` gives a 95 the grade C, because 95 already satisfies the first condition; the A branch can never be reached. With overlapping conditions such as these, put the most restrictive condition first.

A useful check is to ask, for each branch, "Is there any value that can reach this body?" If every value that fails the earlier conditions also fails this one, the branch is unreachable, which almost always signals an ordering mistake. Tracing one value from each intended category, plus the boundary values, catches these errors quickly.

When ranges do not overlap, as with exact matches such as `size == 1` and `size == 2`, the order does not change which branch runs, because at most one condition can be true. Even then, putting the most common case first is a reasonable habit, since it makes the typical path through the code easy to see.

**Figure 3.** Because the first true condition wins, the order of the conditions decides the result whenever the ranges overlap.

Worked Example 5 Order of conditions

### A Chain in the Wrong Order

The conditions are the same as before, but in a different order. Predict each grade.

Code

```
public static String badGrade(int score)
{
    if (score >= 70)
    {
        return "C";
    }
    else if (score >= 80)
    {
        return "B";
    }
    else if (score >= 90)
    {
        return "A";
    }
    else
    {
        return "F";
    }
}
```

Output

```
C
C
F
```

1. 1 **95 and 85.** `score >= 70` is checked first and is `true`, so both get C.
2. 2 **Unreachable branches.** Any score that fails `>= 70` also fails `>= 80` and `>= 90`, so the B and A branches can never run.
3. 3 **60.** Every condition is `false`: F.

**Result:** The output is C, C, F. When ranges overlap, the most restrictive condition must come first; otherwise later branches are never reached.

Common Mistake 3 · Putting a Broad Condition First

In an `if-else-if` chain with overlapping ranges, a broad condition near the top captures values meant for later branches. Order the conditions so that each one catches only the values intended for it, usually from most restrictive to least.

## 5 Chains Versus Separate if Statements

Writing several separate `if` statements is not the same as writing one `if-else-if` chain. Separate `if` statements are independent: each condition is checked, and every body whose condition is `true` runs. A chain stops at the first true condition, so at most one body runs.

Use separate statements for independent checks that may all apply, such as adding several different bonuses. Use a chain for mutually exclusive categories, where exactly one label should apply. Choosing the wrong structure produces duplicate output or missing output, depending on which way the mistake goes.

**Figure 4.** Separate `if` statements are each checked, so several bodies can run. An `if-else-if` chain stops at the first true condition.

Worked Example 6 Separate ifs

### Several Bodies Can Run

Compare these two programs. Predict each output.

Three separate if statements

```
int temp = 35;
if (temp > 30)
{
    System.out.println("hot");
}
if (temp > 20)
{
    System.out.println("warm");
}
if (temp > 10)
{
    System.out.println("mild");
}
```

Output

```
hot
warm
mild
```

One if-else-if chain

```
int temp = 35;
if (temp > 30)
{
    System.out.println("hot");
}
else if (temp > 20)
{
    System.out.println("warm");
}
else if (temp > 10)
{
    System.out.println("mild");
}
```

Output

```
hot
```

1. 1 **Separate ifs.** Each `if` is an independent statement. All three conditions are `true` for 35, so all three lines print.
2. 2 **The chain.** The first condition is `true`, so "hot" prints and the rest of the chain is skipped.

**Result:** The first program prints hot, warm, mild; the second prints only hot. Use `else if` when the cases should be mutually exclusive.

Common Mistake 4 · Forgetting else in a Category Chain

Three separate `if` statements for "hot," "warm," and "mild" can print all three for a single temperature. If a value belongs in only one category, connect the conditions with `else if` so that only the first match runs.

## 6 Choosing a Structure

Nested selection and multiway selection solve different problems. Nesting suits decisions that depend on each other, where a second question only matters after the first is answered. A multiway chain suits one question with several possible answers, where a single value is sorted into exactly one category. Many programs use both: a chain whose branches contain nested decisions, or a nested `if` whose inner part is a chain.

Whatever the structure, the same habits apply. Use braces on every body so the structure is unambiguous, indent consistently so the nesting is visible, and trace with values from every category and every boundary. The table below summarizes when each structure fits.

| Structure | How many bodies can run | Use it when |
| --- | --- | --- |
| Nested if | Inner checked only if outer is true | A second question only makes sense after the first is answered |
| if-else-if with trailing else | Exactly one | Choosing one of several mutually exclusive cases, with a default |
| if-else-if without else | At most one (possibly none) | Mutually exclusive cases where doing nothing is acceptable |
| Several separate ifs | Any number, including all | Independent checks that should each be considered |

| Mistake | Symptom | Fix |
| --- | --- | --- |
| Least restrictive condition first | Later branches never run | Order from most to least restrictive |
| Separate ifs where else-if was meant | Several messages print | Join them with else if |
| Missing trailing else | Some values produce no result | Add a final else for the remaining cases |
| Calling a method on a possibly null reference first | NullPointerException | Check for null in an outer if |

### Four Habits for Nested and Multiway Selection

#### 1. Outside In

Inner conditions are checked only if the outer one is true.

#### 2. First True Wins

An if-else-if chain runs at most one body.

#### 3. Most Restrictive First

Order overlapping conditions so every branch is reachable.

#### 4. Chain or Separate?

else if for exclusive cases; separate ifs for independent checks.

Core Synthesis

Nested if statements consist of `if`, `if-else`, or `if-else-if` statements within `if`, `if-else`, or `if-else-if` statements. The Boolean expression of the inner nested `if` statement is evaluated only if the Boolean expression of the outer `if` statement evaluates to `true`. A multiway selection (`if-else-if`) is used when there is a series of expressions with different segments of code for each condition; no more than one segment of code is executed, based on the first expression that evaluates to `true`, and if no expression evaluates to `true` and there is a trailing `else`, its body is executed.

FiveStudy AP® Computer Science A Study Guide · Selection and Iteration · Nested and Multiway Selection Back to top ↑
