Sub topic 7
Use Arrow-Style Cases That Do Not Fall Through
An arrow-style switch statement lets you give each choice its own action. A statement is an instruction that tells Java to do something. In this kind of switch, the arrow points from a possible choice to the action for that choice.
After the chosen action finishes, Java leaves the switch. It does not run the action under the next choice. Running into the next case without checking for a new match is called fall-through. Arrow-style cases do not fall through, so you do not need a break at the end of each case to prevent it.
This is useful in a menu. If someone chooses to see help, you want to show help. You do not also want to print the message for quitting just because it comes next in the code.
Follow the Arrow From Choice to Action
The selector is the value a switch uses to choose an action. You write it inside the parentheses after the word switch. A case label is a value Java can match against the selector. A rule is the whole choice and action together: the case label, the arrow, and the code to run.
In this program, the selector is the value stored in command. Its type is String, which is Java's type for text. The rule for “help” prints one message, and the rule for “quit” prints a different one. The default rule handles text that matches neither case.
Save the program as CommandMenu.java and run it.
public class CommandMenu {
public static void main(String[] args) {
String command = "help";
switch (command) {
case "help" -> System.out.println("Show available commands");
case "quit" -> System.out.println("Goodbye");
default -> System.out.println("Unknown command");
}
System.out.println("Command check finished");
}
}The program prints “Show available commands” and then “Command check finished”, on separate lines. Trace the run in three steps:
- Java reads command and gets the text “help”.
- The “help” label matches, so Java runs the action to the right of that arrow.
- That action finishes. Java skips the other rules and runs the print line after the switch.
Notice the difference between the “quit” print line and the last print line. The “quit” print line is inside the switch, so it runs only for a matching choice. The last print line is outside the switch, so it runs when the switch finishes normally.
Try changing only the text stored in command. Before each run, predict the first line. Leave the other code alone so you can see how one change to the selector affects the result.
| Text stored in command | First line | Second line |
|---|---|---|
| “help” | Show available commands | Command check finished |
| “quit” | Goodbye | Command check finished |
| “start” | Unknown command | Command check finished |
| “Help” | Unknown command | Command check finished |
For these String cases, the text must match exactly. “Help” differs from “help” in letter case. A space counts too: “help ” has a space at the end, so it does not match “help”. The switch does not change the text before it tries to match it.
Give More Than One Label the Same Action
Suppose you want both “help” and “?” to show the help message. You could copy the print line into two rules, but then a change to the help message would have to be made in two places.
Instead, put both labels after one case and separate them with a comma. Put one arrow after the list. This means “match any one of these values”, not “run one action for each value in the list”. For example, a selector of “?” matches one label in the group, and the shared action runs once.
Put Several Actions in One Rule
Now suppose that help should print two lines: a heading and a list of commands. A block is a group of statements between braces, the characters { and }. Put a block to the right of the arrow when the rule needs several statements. Java runs the statements in that block from top to bottom.
The next program uses both changes. It groups “help” and “?” into one rule and gives that rule a two-line block. Save it as HelpMenu.java and run it.
public class HelpMenu {
public static void main(String[] args) {
String command = "?";
switch (command) {
case "help", "?" -> {
System.out.println("Available commands:");
System.out.println("help, ?, quit");
}
case "quit" -> System.out.println("Goodbye");
default -> System.out.println("Unknown command");
}
System.out.println("Command check finished");
}
}The output starts with “Available commands:” and then “help, ?, quit”. The third line is “Command check finished”. The first two lines come from one rule, not from two different cases. When Java reaches the closing brace of the help block, it leaves the switch rather than moving into the “quit” rule.
Change command to “quit” and run it again. Now neither help line appears. The program prints “Goodbye” and then the line after the switch. This gives you a quick way to check that you put the help lines in the right place.
Read the Braces and Semicolons
A semicolon is the mark that ends many Java statements. Look at the two forms used on the right of the arrows:
- For a single call to System.out.println, put a semicolon after the call. A call is an instruction to run a named action. Here that action prints a line of text.
- For a block, each print call still ends in a semicolon. Do not add an extra semicolon after the block's closing brace.
In HelpMenu, the indented closing brace just above the “quit” rule ends the help block. The closing brace just above the last print line ends the entire switch. Indentation, or the spaces at the start of a line, helps you see those levels. The braces are what Java uses to tell where each block ends.
When you add a second print line to a rule, add braces around both lines. Just placing two print calls after an arrow, one below the other, does not make both calls part of the rule.
Decide What Happens When Nothing Matches
For the kind of String switch statement in these examples, default is optional. If no label matches and there is no default, Java does nothing inside the switch. It then continues with the next statement.
That can be useful when a choice gets an extra message but all other choices should pass through quietly. For example, this program adds a message only for “preview”. Save it as PreviewNotice.java and run it.
public class PreviewNotice {
public static void main(String[] args) {
String mode = "normal";
switch (mode) {
case "preview" -> System.out.println("Preview mode is on");
}
System.out.println("Ready");
}
}With “normal”, the program prints only “Ready”. If you change mode to “preview”, the program prints “Preview mode is on” and then “Ready”. In both runs, the last line is outside the switch.
For a command menu, keeping default is often helpful. If “start” is not a command, the user sees “Unknown command” instead of getting no menu message at all. For the preview notice, doing nothing inside the switch is part of the design. In either program, the key is to know what should happen when no label matches.
Check Common Mistakes
A compile error means Java could not prepare the program to run. If you get one after editing a rule, check the arrow, the labels, and the end of the action. If the program runs but the output surprises you, check the exact text in the selector and which braces hold the print line.
| What you see | What to check |
|---|---|
| A rule with two choices is rejected | Use one case followed by both labels with a comma between them. Put the arrow after the last label. |
| Java reports a duplicate case | A label can appear only once in a switch. If “help” is in a group, do not also give “help” its own rule. |
| Java rejects an added print line | Put both print calls for that rule inside one pair of braces. End each call with a semicolon. |
| Java rejects a mix of arrows and colons | Use one rule style throughout a switch. In these examples, use the arrow made from a hyphen followed by a greater-than sign, with no space between them. |
| A message appears for every choice | Check whether its print call sits after the switch. Move it into the chosen rule if it belongs there. |
| You get “Unknown command” for text that looks right | Compare capital letters and check for extra spaces. A String label matches the exact text. |
After each edit, try one value from each rule you expect to run and one value with no match. If a rule has two labels, try both. For HelpMenu, that means testing “help”, “?”, “quit”, and something like “start”. Check both what appears and what does not. In particular, seeing the help text is only half the check for “?”. You should also see that “Goodbye” and “Unknown command” did not print.
When you trace an arrow-style switch by hand, follow just one path. Find the matching label, run its action or block, and then look below the switch. If there is no match, use default if it is present. The next rule in the file is not the next step in the run.
Practice Tracing and Editing Rules
Try to answer each question before checking the answer. For the edits, run the program with both a matching and a nonmatching value so you can check where each message appears.
Exercise
In HelpMenu, what lines print when command is "help"? What changes when command is "?"?
Show answer
Both values print "Available commands:", then "help, ?, quit", then "Command check finished". Each value matches a label in the same rule, so the output does not change.
Exercise
Change HelpMenu so "exit" does the same thing as "quit" without copying the print call. What prints when command is "exit"?
Show answer
Add "exit" to the quit rule after a comma and before the arrow. With "exit", the program prints "Goodbye" and then "Command check finished".
Exercise
In CommandMenu, remove the default rule and set command to "start". Does the program print nothing at all?
Show answer
No. Nothing runs inside the switch because no label matches. The line after the switch still prints "Command check finished".
Exercise
In HelpMenu, add a print call for "Type quit to leave" so it appears only for "help" or "?". Where does it go, and which input can you use to check that it does not appear for a different rule?
Show answer
Put it inside the help block, after the two existing print calls and before the block's closing brace. Run with "quit" to check that you get "Goodbye" and "Command check finished" but not the new help line.