Concepts / Multiway If Statements in Java

Multiway If Statements in Java

A switch statement and a multiway if statement can have the same effect, and the source notes that any switch can be replaced by a multiway if.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

Predicting Which Message Prints

Many programs need to pick one of several actions depending on the value of a single variable. A student might want one message for the number 1, another message for the numbers 2, 4, and 8, and a different message for every other number. Java offers two common ways to write this kind of decision. One is a chain of if, else if, and else statements, which this article calls a multiway if statement. The other is the switch statement, which lists the possible values as cases. The two forms are closely related, and this article looks at how they relate and how to decide which one fits a given problem.

What do you think happens?

Suppose N holds the value 2. Using the multiway if chain shown in the next section, which lines print? Commit to an answer before reading the reveal.

  • Only the message for 1 prints

  • Only the message for 2, 4, or 8 prints

  • Only the message for everything else prints

  • Both the message for 1 and the message for 2, 4, or 8 print

Reveal answer
Answer:

Only the message for 2, 4, or 8 prints.

The first test asks whether N equals 1, which is false for the value 2. The next test asks whether N equals 2, 4, or 8, which is true. That branch runs, and the final else is skipped. Only one branch ever runs for a given value.

Two Forms for Choosing Among Many Cases

The multiway if statement and the switch statement solve the same kind of problem. In both, a program examines a value and runs exactly one group of statements based on what that value is. The difference lies in how each form expresses the decision. A multiway if statement is a sequence of separate tests, each one a condition that is either true or false. A switch statement names the variable once and then lists the values it might hold as cases.

Because both forms make the same kind of choice, the source states that a multiway if statement can have exactly the same effect as a switch statement that handles the same cases. The source also notes that any switch can be replaced by a multiway if. Understanding why these two forms match is the key to reading either one with confidence.

Reading the Chain as Ordered Questions

The best way to read a multiway if statement is as a sequence of questions asked in order. Each question is a test on the variable. The first test that is true decides which statements run. The final else catches every value that no earlier test accepted. The tests run in order and stop at the first success, so once a branch is chosen, the remaining else if tests and the final else are skipped.

java
Output
two, four, or eight
Notes on the code
  • The first test checks whether N equals 1.
  • The second test groups the values 2, 4, and 8 with the or operator.
  • The final else handles every value that no earlier test accepted.

Notice that each test compares the same variable, N, with a constant. That shared pattern is exactly what a switch statement is built to express. The diagram below shows the decisions this chain makes. Each diamond is one test, and each box is the output that test leads to when it succeeds.

N == 1print oneN == 2 or N == 4 or N== 8print two, four, oreightendprint something elsetruefalsetruefalse
When N equals 2, which test is checked first, which branch is skipped, and which branch finally executes?

Tracing N Through the Chain

Worked example

Tracing three different values of N

For each of the values 1, 2, and 6, determine which branch of the multiway if chain runs and which line prints.

  1. 1
    Value 1

    The first test, N == 1, is true. The message for 1 prints, and the remaining tests and the final else are skipped. Only one comparison was needed.

  2. 2
    Value 2

    The first test, N == 1, is false, so control moves to the next test. The test N == 2 or N == 4 or N == 8 is true because N equals 2. The message for 2, 4, or 8 prints, and the final else is skipped.

  3. 3
    Value 6

    The first test is false because 6 is not 1. The second test is also false because 6 is not 2, 4, or 8. No earlier test accepted the value, so control reaches the final else and the something else message prints. This value passed through every test before reaching its branch.

Result

The values 1, 2, and 6 print the one message, the two, four, or eight message, and the something else message, respectively. A value far down the chain must pass every earlier test before reaching its branch, while a value matching the first test is handled after just one comparison.

The Switch Equivalent

A switch statement names the variable once, in the parentheses after the keyword switch. Then each case label lists one value that the variable might hold. When a case label matches, control enters the statements beneath it. A break statement ends the switch so that control does not fall through into the next case. Cases that share one set of statements can be stacked, with no statements between their labels. That stacking is how the switch form covers 2, 4, and 8 together.

java
Output
two, four, or eight
Notes on the code
  • The variable n is named once, in the parentheses after switch.
  • The stacked labels 2, 4, and 8 share one set of statements.
  • The default label plays the role that the final else played in the chain.

Why the Two Forms Match

Set the two versions side by side and the correspondence is direct. The variable named once in the switch appears in every test of the chain. Each stacked case label corresponds to one comparison in an or group of the chain. The default label corresponds to the final else. For the value 2, both versions reach the same branch and print the same line. This is why the source can say the two forms have the same effect on the same cases.

N written in everytestGroups joined with orTests checked inorderN named onceEach value on its owncasebreak ends each case
How does the switch express the same decision as the multiway if chain, and where does each form repeat the variable or the value groups?

Choosing Between Readability and Efficiency

The source gives two reasons a programmer might prefer one form. The first is readability. In the multiway if chain, the variable N is written out again in every test, and the value groups are expressed as repeated comparisons joined by or. In the switch form, the variable is named once and each possible value sits on its own labeled line, so a reader can scan the case labels to see the full list of handled values.

The second reason is efficiency. The source says a switch statement might be more efficient because the computer can jump directly to the correct case, instead of working through a series of tests to reach it. In a multiway if chain, a value must be compared against each earlier test. The source uses the word might, so this is a possibility that depends on how the program is compiled and run, not a guaranteed speed gain.

ConsiderationMultiway if chainSwitch statement
VariableWritten out in every testNamed once in the parentheses
Value groupsJoined with or in a conditionStacked case labels
Catch-all branchFinal elsedefault label
Evaluation orderTests run in order and stop at the first successControl can go straight to the matching case
SpeedA value must pass earlier testsThe source says it might be more efficient
ReadabilityRepeated comparisons take effort to scanCase labels list the handled values clearly

Comparing the two forms by readability and by how they evaluate conditions

Mistakes When Writing Multiway Chains

Because the tests run in order and stop at the first success, the order of the tests is part of the meaning of the chain. The mistakes below come from forgetting that, or from forgetting how the switch form differs.

  • Common mistake

    Assuming every branch runs when its condition is true

    What it looks like
    if (n == 2 || n == 4 || n == 8) appears before if (n == 2) in a second chain. The value 2 is caught by the first test, so the second branch never runs.
    Why it fails

    Only the first true test decides which statements run. Later tests are skipped once a branch is chosen.

    Do this instead

    Place the most specific tests first and remember that the chain stops at the first success.

  • Common mistake

    Expecting a switch case to end without break

    What it looks like

    A case for 2 without break runs its statements and then continues into the case for 4.

    Why it fails

    Control falls through into the next case unless a break ends the switch.

    Do this instead

    End each case that should stop with a break statement.

  • Common mistake

    Assuming a switch is always faster

    Why it fails

    The source says a switch might be more efficient, which is a possibility rather than a guarantee.

    Do this instead

    Choose the form that reads most clearly and treat any speed difference as something that depends on how the program is compiled and run.

Practicing the Trace

EASY

Using the multiway if chain from the earlier section, what does the program print when n holds the value 8? Then repeat the trace for the value 3. For each value, name every test that is checked and say which branch finally runs.

Hints
  • Start with the test n == 1 and decide whether it is true for the value you are tracing.
  • If the first test is false, check whether the second test accepts the value.
  • Remember that once a branch is chosen, the remaining tests and the final else are skipped.

Key Takeaways

  • A multiway if statement is a chain of if, else if, and else statements, and its tests run in order and stop at the first true test.
  • The final else in a multiway if chain catches every value that no earlier test accepted.
  • A switch statement names the variable once and lists values as cases, which can make the code easier to read, and any switch can be replaced by a multiway if with the same effect.
  • A switch statement might be more efficient because the computer can jump directly to the correct case, but this is a possibility rather than a guarantee.
  • Readability and efficiency are separate considerations, and a programmer weighs both when choosing between the two forms.