Using break in Switch Statements
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.
Try it: while Loops, break and continue
How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.
How it works
- Evaluate the condition. If it is False, skip the body and continue after the loop.
- If it is True, run the body from the top, then go back and evaluate the condition again.
- continue skips the rest of the body and goes straight back to the condition check.
- break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
- If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.
Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.
Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.
Loading the simulation…
Picking One Action from Several Values
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 everything else. Java offers two common ways to write this. 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. This article looks at how the two forms 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 message prints? Commit to an answer before reading the reveal.
Reveal answer
Two, four, or eight
The test N == 1 is false for 2, so control moves to the next test. The test N == 2 || N == 4 || N == 8 is true, so that branch runs and the final else is skipped.
Tracing a Multiway if Chain
Read a multiway if statement as a sequence of questions asked in order. Each question is a test on N, and the first test that is true decides which messages print. The final else catches every value that no earlier test accepted. The tests run in order and stop at the first success. Once a branch is chosen, the remaining else if tests and the final else are skipped.
- The first test compares N with 1 only
- The second test groups 2, 4, and 8 with repeated comparisons joined by ||
- The final else handles every value no earlier test accepted
Tracing N = 2 and N = 9 through the chain
Which message prints for N = 2, and which for N = 9, in the multiway if chain above?
- 1Trace N = 2
Test N == 1. It is false, so skip the branch that prints One. Test N == 2 || N == 4 || N == 8. N == 2 is true, so the whole condition is true. Print Two, four, or eight. The final else is skipped.
- 2Trace N = 9
Test N == 1. It is false. Test N == 2 || N == 4 || N == 8. All three comparisons are false, so the condition is false. No earlier test accepted 9, so control reaches the final else and prints Something else.
- 3Compare the number of tests
N = 2 needs two tests before its branch runs. N = 9 needs both tests and then the final else. A value that matches the first test would be handled after only one comparison.
N = 2 prints Two, four, or eight. N = 9 prints Something else.
Writing the Same Logic as a Switch
The source states that the multiway if statement above has exactly the same effect as a switch statement that handles the same cases. Notice what the tests have in common. Each one compares the same variable, N, with a constant. That shared pattern is exactly what a switch statement is built to express. A switch names the variable once, in the parentheses after the keyword switch. Then each case label lists one value that the variable might hold.
- N is named once, in the parentheses after switch
- Each case label lists one value N might hold
- Cases 2, 4, and 8 are stacked with no statements between their labels, so they share one set of statements
- The default label plays the role of the final else in the chain
When a case label matches the value of the variable, control enters the statements beneath that label. Stacking case labels with no statements between them is how a single set of statements covers several values at once. In the example above, the stacked labels 2, 4, and 8 all lead to the same println call.
How break Stops Fall-Through
A break statement ends the switch so that control does not fall through into the next case. Fall-through is what happens when control keeps moving down the switch body into the statements of the following case. Without a break, the statements under the matching label run, and then the statements under the next label run too, until a break or the end of the switch is reached.
switch (N) {
case 1:
System.out.println("One");
case 2:
case 4:
case 8:
System.out.println("Two, four, or eight");
break;
}With N = 1 and no break after the case 1 statements, the program prints One and then also prints Two, four, or eight, because control falls into the next case.
switch (N) {
case 1:
System.out.println("One");
break;
case 2:
case 4:
case 8:
System.out.println("Two, four, or eight");
break;
}With N = 1 and a break after the case 1 statements, the program prints only One, because the break ends the switch.
Mistakes Beginners Make with break
Common mistake Forgetting break at the end of a case
What it looks likeCase 1 prints One but has no break, so N = 1 also prints Two, four, or eight.
Why it failsControl falls through into the next case instead of ending the switch.
Do this insteadPlace a break after each case's statements unless fall-through is intended.
Common mistake Expecting a multiway if chain to test every condition
What it looks likeAssuming the test N == 8 runs for N = 2 after the first branch has already been chosen.
Why it failsThe tests run in order and stop at the first success, so the remaining else if tests and the final else are skipped.
Do this insteadTrace the chain from top to bottom and stop at the first true test.
Common mistake Treating stacked case labels as separate actions
What it looks likeWriting case 2: then case 4: with no statements between them and expecting different output for each.
Why it failsStacked labels share the statements that follow them, so both values reach the same code.
Do this insteadUse stacked labels only when the values should share one set of statements.
Common mistake Assuming the switch form is always faster, when the source says only that it might be more efficient
Choosing Between switch and Multiway if
The source notes that a switch statement can be easier to read than a multiway if statement. In the chain, the variable N is written out again in every test, and value groups are expressed with repeated comparisons joined by ||. 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 source also says that 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. 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. Efficiency and readability are separate considerations. A faster form is not automatically the clearer one, and a clearer form is not automatically faster. A programmer weighs both when choosing.
| Consideration | Multiway if chain | Switch statement |
|---|---|---|
| Where the variable appears | Repeated in every test | Named once after switch |
| How values are listed | Repeated comparisons joined by || | One labeled case per value |
| Grouping shared actions | Combined inside one condition | Stacked case labels with no statements between |
| Ending each branch | Implicit; the chain stops at the first true test | Requires break to avoid fall-through |
| Efficiency | Tests run in order until one succeeds | Source says it might allow a direct jump to the case |
Comparing the two forms for choosing one action from several values of N
Practice Tracing Both Forms
Using the multiway if chain and the switch version from this article, determine which message prints for N = 4, N = 1, and N = 6. For each value, list the tests or case labels that are checked, and say which branch runs.
Hints
- For the multiway if chain, start at N == 1 and move down until a test is true.
- In the switch version, look for the case label that matches the value of N.
- N = 6 matches no test or case label, so think about which branch handles it.
Remove the break after the case 1 statements in the switch version. Predict which messages print for N = 1, then check your answer by tracing control flow from the matching label.
Hints
- Control enters the statements under the matching label.
- Without a break, control continues into the statements under the next label.
Key Takeaways
- A multiway if chain tests conditions in order and stops at the first true test, with the final else handling any value no earlier test accepted.
- A switch statement names the variable once and lists values as cases, and the source states it can have the same effect as a multiway if statement covering the same cases.
- A break statement ends the switch so control does not fall through into the next case; stacked case labels share one set of statements.
- The source says a switch might be more efficient and can be easier to read, but efficiency and readability are separate considerations to weigh when choosing.