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.
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.
1Nested 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.
if, the Boolean expression of the inner if is evaluated only if the outer expression is true.Choosing a Gate
Predict the output for each visitor.
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";
}
}
child gate
main gate
buy a ticket at the door
- 1
gate(true, 9). The outer condition istrue, so the inner one is checked: 9 < 12, child gate. - 2
gate(true, 30). Outertrue; innerfalse: main gate. - 3
gate(false, 9). Outerfalse: the else body runs, and the age is never examined.
if is reached only when the outer condition is true.Checking Before Using
The inner condition calls a method that would fail on null. Predict the output.
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");
}
no code entered
- 1Outer condition.
code != nullisfalse. - 2The inner condition is never evaluated, so
code.length()is never called and noNullPointerExceptionoccurs. - 3The outer else runs: "no code entered".
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.
2Multiway 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.
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) |
Letter Grades
Predict each grade.
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";
}
}
A
B
B
F
- 195. The first condition is
true: A. - 285. First
false, secondtrue: B. The remaining conditions are not checked. - 380.
80 >= 80istrue, so B. The boundary belongs to the higher grade because of>=. - 442. No condition is
true, so the trailing else runs: F.
3The 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.
When No Condition Is True
This chain has no final else. Predict the output for a size of 3.
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");
start
end
- 1Both conditions are
falsefor 3. - 2No trailing else. With no
else, nothing in the chain runs. - 3Execution continues after the chain: "end".
else may run no body at all; with one, exactly one body always runs.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.
4The 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.
A Chain in the Wrong Order
The conditions are the same as before, but in a different order. Predict each grade.
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";
}
}
C
C
F
- 195 and 85.
score >= 70is checked first and istrue, so both get C. - 2Unreachable branches. Any score that fails
>= 70also fails>= 80and>= 90, so the B and A branches can never run. - 360. Every condition is
false: F.
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.
5Chains 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.
if statements are each checked, so several bodies can run. An if-else-if chain stops at the first true condition.Several Bodies Can Run
Compare these two programs. Predict each output.
int temp = 35;
if (temp > 30)
{
System.out.println("hot");
}
if (temp > 20)
{
System.out.println("warm");
}
if (temp > 10)
{
System.out.println("mild");
}
hot
warm
mild
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");
}
hot
- 1Separate ifs. Each
ifis an independent statement. All three conditions aretruefor 35, so all three lines print. - 2The chain. The first condition is
true, so "hot" prints and the rest of the chain is skipped.
else if when the cases should be mutually exclusive.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.
6Choosing 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.
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.