Sub topic 6
Read Colon-Style Cases and Control Fall-Through with break
A colon-style switch is a Java statement that uses labels such as case 2: to mark where code can start running. The label tells Java where to start, not where to stop. Once Java starts at a label, it can keep running code under the next label. That behavior is called fall-through.
Use break; to stop that flow. In a switch like the ones in this chapter, break; sends Java to the first statement after the closing brace of the switch. It does not end the program.
Trace a Menu Choice
The selector is the value inside the parentheses after switch. A case label marks the starting point for a matching value. A default: label marks the starting point when no case matches.
Save this program as Main.java. Compile it with javac Main.java, then run it with java Main. For each later program, replace the whole file and run those commands again.
public class Main {
public static void main(String[] args) {
int menuChoice = 2;
switch (menuChoice) {
case 1:
System.out.println("Start");
break;
case 2:
System.out.println("Settings");
break;
default:
System.out.println("Unknown choice");
}
System.out.println("Back at the menu");
}
}Trace the program in two parts: find the starting point, then follow the code.
- Java reads
menuChoice. Its value is2, so execution starts just aftercase 2:. - Java prints
Settings. It does not run the print statement undercase 1:because that code is above the starting point. - Java reaches
break;and leaves theswitch. It skips the print statement underdefault:. - Java prints
Back at the menu. This line is after theswitch, so thebreak;does not skip it.
Try changing menuChoice to 1, then to 7. Predict the output before each run.
| `menuChoice` | Starting label | First line printed | How the `switch` ends |
|---|---|---|---|
| `1` | `case 1:` | `Start` | Java reaches `break;`. |
| `2` | `case 2:` | `Settings` | Java reaches `break;`. |
| `7` | `default:` | `Unknown choice` | Java reaches the closing brace. |
All three runs print Back at the menu as the second line. Notice that default: has no break; in this version. There is no more code inside the switch after its print statement, so Java simply reaches the end.
What Changes When a break Is Missing?
Set menuChoice back to 2. Remove only the break; after System.out.println("Settings");. Keep the break; under case 1:. Compile and run the program again.
This time it prints Settings, then Unknown choice, then Back at the menu. The value 2 still matches case 2:. The mistake happens after the match. With no break; to stop it, Java continues into the print statement under default:.
The question in the diagram compares two versions of the program. It is not a test you add to the Java code. In the first version, the next statement is break;. In the second version, the next statement is the print under default:.
To see that happen with a numbered case, restore the break; under case 2:. Now remove the break; under case 1: and set menuChoice to 1. The program prints Start, then Settings, then Back at the menu. It reaches the break; under case 2: and stops before default:. Java does not care that the break; sits under a label for a different value. What matters is that Java reaches it.
Read default Like Any Other Starting Label
Most code puts default: last so readers can find it easily. Java does not require that position. If no case matches, Java starts at default: wherever it appears. If a case does match, Java starts at that case even if default: appears earlier in the file.
Try this program with level set to 2, then to 9. The unusual position of default: makes it easier to see the difference between starting and stopping.
public class Main {
public static void main(String[] args) {
int level = 2;
switch (level) {
case 1:
System.out.println("Level one");
break;
default:
System.out.println("Unknown level");
break;
case 2:
System.out.println("Level two");
break;
}
}
}- With
levelset to2, Java starts atcase 2:and printsLevel two. It skips the code underdefault:, even though that code comes first. - With
levelset to9, no case matches. Java starts atdefault:and printsUnknown level. Thebreak;stops it before the print undercase 2:. - If you remove the
break;underdefault:and run with9again, Java printsUnknown leveland thenLevel two. It starts atdefault:and falls through into the next case.
A colon-style switch like this one can also leave out default:. Try removing the default: label, its print statement, and its break;. With level set to 9, the program now prints nothing. With no matching label and no default:, Java skips the whole body of the switch. Leave out default: only when doing nothing for unlisted values is what you want.
Share Work on Purpose
Not all fall-through is a mistake. Sometimes two values should run the exact same code. Put their labels next to each other with no statements between them. Both labels then lead to the same work.
In this program, String is Java's type for text. The program accepts either y or yes for the same response.
public class Main {
public static void main(String[] args) {
String answer = "y";
switch (answer) {
case "y":
case "yes":
System.out.println("You agreed");
break;
case "n":
case "no":
System.out.println("You declined");
break;
default:
System.out.println("Please answer yes or no");
}
}
}With answer set to "y", Java starts at case "y":. There is nothing to run before the next label, so Java reaches System.out.println("You agreed");. With "yes", it starts one label lower and reaches the same print statement. Either way, it prints You agreed just once. The break; after that statement protects the whole group from falling through into the code for n and no.
Try putting a break; between case "y": and case "yes":. Now "y" prints nothing, but "yes" still prints You agreed. The first label no longer leads to the shared work. Remove that extra break; to restore the group.
Run an Extra Step Before Shared Work
Two cases can also share a final step even when one of them does extra work first. This example prints messages to show the steps; it does not change any files.
public class Main {
public static void main(String[] args) {
String action = "save-and-close";
switch (action) {
case "save-and-close":
System.out.println("Saving the document");
// Fall through: close the document after saving.
case "close":
System.out.println("Closing the document");
break;
default:
System.out.println("Unknown action");
}
}
}Starting at case "save-and-close": prints both messages. Starting at case "close": prints only Closing the document. Java runs downward from the chosen label. It never goes back up to run the save step.
A comment is a note in the code that Java does not run. The comment here tells the reader why the first case has no break;. Without the note, the missing break; could look like a bug. Even with a comment, use this pattern with care. If someone moves the close case or adds a new case between the two, they can change what save-and-close does. For cases that should do exactly the same work, prefer labels placed together with no statements between them.
Find and Fix Unwanted Fall-Through
The compiler is the tool that checks and prepares your Java code to run. A missing break; does not have to be a compiler error. Java allows fall-through because it can be useful. That means a program can compile and still run more code than you meant it to.
| What you notice | What to check |
|---|---|
| The menu prints both `Start` and `Settings`. | Start at `case 1:` and look for a `break;` before the next print statement. |
| A valid choice also prints `Unknown choice`. | Check whether code from a matching case can reach the print under `default:`. |
| `"yes"` works, but `"y"` prints nothing. | Look for a `break;` between the two labels that should share a print statement. |
| `break;` runs, but a line still prints afterward. | Check whether the line is after the `switch`. `break;` does not skip that line. |
Indentation, the spaces at the start of a line, helps people see which code belongs together. It does not stop fall-through. A pair of braces around the statements for a case can group them into a block, but the closing brace of that block is not a break; either. Java can leave the block and continue into the next case.
When checking your own code, test one value for every case label and one value that matches none. If several labels share work, try each one: testing only "yes" would not catch a stray break; after case "y":. For each test, write the expected lines in order before running the program. Check for extra lines as well as missing ones. Seeing Settings is not enough if Unknown choice follows it.
Practice
Exercise
In the first menu program, set menuChoice to 1 and remove both break statements. What prints, and in what order?
Show answer
It prints Start, Settings, Unknown choice, and Back at the menu, in that order. Java starts at case 1 and runs to the end of the switch before running the line after it.
Exercise
In the level program, default appears above case 2. Why does level 2 print only Level two?
Show answer
Java starts at the matching case 2 label. The print under default is above that starting point, so Java never reaches it.
Exercise
Add support for the text "yeah" in the answer program so it prints You agreed. Where should the new label go, and does it need its own break?
Show answer
Add case "yeah": beside case "y": and case "yes":, before the shared print statement. It does not need its own break. The break after the print statement ends the switch for all three labels.
Exercise
A teammate adds a break after Saving the document to prevent fall-through. What changes for save-and-close, and what should you do if the command must still do both steps?
Show answer
The command now prints only Saving the document because the new break stops it before the close step. Remove that break and keep the fall-through comment so the next reader knows both steps are intended.