Sub topic 5
Match a Selector Value to a case or default
A menu asks you to enter 1 to start, 2 to open settings, or 3 to quit. Once your program has the number, it needs to pick the right action. A switch statement is a Java instruction that uses one value to decide which action to run.
The selector is the expression inside the parentheses after switch. An expression is a piece of code that produces a value. The selector can be as simple as a variable name. A case label names a value to match, such as 2. The default label gives Java an action to run if none of the case labels match.
The key question when you read a switch is: What value does Java have to match? Work that out first. Then look for that value in the labels.
Trace a menu choice
This program starts with a choice of 2. It does not ask you to type a number. For now, changing the number in the code lets you test each path without adding code to read input.
Save the program as MenuDemo.java. The examples in this chapter use arrow labels, which work in Java 14 or later. Read the arrow as “run this action for this label.”
public class MenuDemo {
public static void main(String[] args) {
int menuChoice = 2;
switch (menuChoice) {
case 1 -> System.out.println("Start");
case 2 -> System.out.println("Settings");
case 3 -> System.out.println("Quit");
default -> System.out.println("Unknown choice");
}
System.out.println("Done checking the menu");
}
}Run the file from the folder where you saved it:
java MenuDemo.javaJava reads the value of menuChoice, which is 2. It finds the label case 2 and prints “Settings.” There is a match, so Java does not run the default action. After the switch ends, Java prints “Done checking the menu.” That last line is outside the switch. It is not part of any case.
Now test the program with the numbers in the table. For each row, change only the number assigned to menuChoice. Predict the output before you save and run the file again.
| Value of menuChoice | Label used | First line printed |
|---|---|---|
| 1 | case 1 | Start |
| 2 | case 2 | Settings |
| 3 | case 3 | Quit |
| 8 | default | Unknown choice |
Every run still prints “Done checking the menu” on the second line. That gives you two things to check: which action Java picked, and where the program went next.
Notice what happens with 8. It is a valid value for an int, which is Java’s type for whole numbers within a set range. But it is not one of the menu choices listed in the switch. Java does not treat 8 as a mistake in the code. It looks for a match and uses default because it finds none.
Find the value Java actually matches
The selector does not have to be just a variable name. It can also use a calculation. In MenuDemo.java, set menuChoice to 1 and change the selector from menuChoice to menuChoice + 1. Leave the labels and actions as they are. Before you run it, ask yourself whether Java will print “Start” or “Settings.”
It prints “Settings.” Java works out the selector once when it reaches the switch. The result of 1 + 1 is 2, so case 2 matches. The calculation does not change the value stored in menuChoice. Java matches the result of the calculation, not the original value in the variable. When you see a calculation in the selector, write down its result before looking at the labels.
The type of the selector matters too. A type tells Java what kind of value it is working with. Here are three common types you can use in a switch like the one in this chapter.
| Selector type | What it holds | Example case label |
|---|---|---|
| int | A whole number | case 2 |
| char | A single character, written in single quotes | case 'A' |
| String | Text, written in double quotes | case "open" |
The number 2, the character '2', and the text "2" can all look the same when printed. Java still treats them as different kinds of values. If your selector is an int, writing case "2" does not make Java turn text into a number. Java rejects the code before the program runs. Use a label that goes with the selector type.
Give each case one clear meaning
In the menu program, the label case 2 names the value, and the print instruction after the arrow names the action. These are two separate parts. If you change “Settings” to “Open settings,” the switch still matches 2. If you change the label from case 2 to case 5, the action stays the same, but now only 5 matches it. This is useful when you change a menu: decide whether you are changing the choice itself or just the text the program shows.
You cannot list the same case value twice in one switch. If two labels both say case 2, Java rejects the program. Even if both actions print the exact same line, the duplicate is still an error. If you want to change what 2 does, edit the action for case 2 instead of adding another case 2.
For the kinds of labels in this chapter, Java must know each label’s value before the program runs. A literal is a value written directly in code, such as 2 or "open". Literals make good labels because their values are clear right where you read them. You may also see labels that use named constants. A named constant is a name for a fixed value. For example, a name like SETTINGS can stand for 2 if it is declared as a final int and set directly to 2. The keyword final means the variable cannot be assigned a new value later. A plain int variable such as menuChoice is not a valid case label just because it happens to hold 2 in one run.
Decide what should happen when nothing matches
The default action is a fallback: it runs when there is no matching case. You can write at most one default label in a switch. It does not stand for a special number like 0. In the menu program, it handles 0, 8, and any other int value you did not list.
In a switch statement like these, default is optional. If there is no match and no default, Java skips the actions in the switch and continues after it. This can be useful when a program only needs to act on a few values.
For example, imagine a drawing program that handles letter keys. In this part of the program, 'C' selects a circle and 'S' selects a square. Other keys should leave the selected tool alone. Save this example as DrawingKeys.java.
public class DrawingKeys {
public static void main(String[] args) {
char key = 'X';
switch (key) {
case 'C' -> System.out.println("Circle tool selected");
case 'S' -> System.out.println("Square tool selected");
}
System.out.println("Key check finished");
}
}Run it with the command below. With 'X', it prints only “Key check finished.” Change 'X' to 'C', save the file, and run it again. This time it prints “Circle tool selected” and then “Key check finished.”
java DrawingKeys.javaThe right choice depends on what the person using the program needs. In the menu, silence would leave someone wondering whether the program saw their choice. An “Unknown choice” message tells them why nothing happened. In the drawing example, the goal is to ignore other keys, so there is no need for a message each time one is pressed.
To see the difference in the original program, restore the selector to menuChoice and set the value to 8. Run it once with default in place. Then remove only the default line and run it again. Both runs finish the menu check. Only the first tells you the choice was unknown.
Match text exactly
A switch can also match a String. For the labels shown here, Java looks for the same characters in the same order. It cares about capital letters and spaces. This is handy when commands must be exact, but it can surprise you when the text comes from a person typing.
Save this program as DoorCommand.java. There is a space after the word open in the value assigned to command. Keep that space for the first run.
public class DoorCommand {
public static void main(String[] args) {
String command = "open ";
switch (command) {
case "open" -> System.out.println("Opening the door");
case "close" -> System.out.println("Closing the door");
default -> System.out.println("Unknown command");
}
}
}java DoorCommand.javaYou will see “Unknown command.” It is easy to miss the extra space on the screen, but Java compares it as part of the text. Try the values below by changing only the text between the quotation marks in the first line of main.
| Text in command | Output | Why |
|---|---|---|
| "open" | Opening the door | The text matches the open label exactly. |
| "open " | Unknown command | The extra space is part of the value. |
| "Open" | Unknown command | Capital O and lowercase o are different. |
| "close" | Closing the door | The text matches the close label exactly. |
| "" | Unknown command | The empty string has no characters and does not match either label. |
If you decide that spaces at the ends should not matter, you can remove them before matching. Java’s String method named strip removes whitespace from the start and end of text. A method is a named piece of code that does a job. Whitespace includes spaces and tabs. To try it, restore the value "open " and change the selector from command to command.strip(). The selector now produces "open", so Java prints “Opening the door.” The original command variable still holds the text with the space. Try "Open" again with the new selector. It still does not match because strip does not change capital letters.
Check a switch that surprises you
First decide whether there is a problem with the code or with a value the program received. If Java will not run the program, check that each label fits the selector type and that no two labels name the same value. Adding default will not repair a label that Java rejects.
If the program runs but picks an unexpected action, trace one run rather than changing several things at once:
- Write down the value the selector produces on that run. Include the result of any calculation or text cleanup.
- Find the label with that exact value. With text, check the capital letters and any spaces.
- If no label matches, look for default. If there is no default, look at the first line after the switch to see what runs next.
For the door program, this trace explains why adding another copy of the "open" label would not help. The problem is not a missing action for "open". The program already has one. The value being matched is "open " with a space. Once you know the value Java actually sees, you can decide whether to accept it or keep the match strict.
Exercise
In MenuDemo.java, suppose menuChoice holds 2, but you change the selector to menuChoice + 1. What two lines does the program print?
Show answer
It prints “Quit” and then “Done checking the menu.” The selector produces 3, so case 3 matches.
Exercise
In DrawingKeys.java, you set key to lowercase 'c'. The program still has a label for uppercase 'C' and no default. What does it print?
Show answer
It prints only “Key check finished.” Lowercase 'c' does not match uppercase 'C', so Java skips the switch actions.
Exercise
In DoorCommand.java, the selector is command.strip() and command holds " Close " with a space on each end. Which action runs, and why?
Show answer
The default action prints “Unknown command.” The selector produces "Close" without the spaces, but that still does not match the lowercase label "close".