The switch Statement
A vending machine doesn't ask a series of questions. You press B4, and it goes straight to slot B4.
In Making Decisions: if and else, you built else if chains that checked ranges, like score >= 90. Chains work for everything, but sometimes they get repetitive. Look at this:
int day = 3;
if (day == 1) {
System.out.println("Monday");
} else if (day == 2) {
System.out.println("Tuesday");
} else if (day == 3) {
System.out.println("Wednesday");
} else {
System.out.println("Some other day");
}Every line checks the same variable against a different exact value. When your decision looks like that, a switch says the same thing more cleanly.
A vending machine
At a vending machine, you don't answer "Is it A1? No. Is it A2? No. Is it A3?" You type a code, and the machine jumps straight to the matching slot. If the code doesn't match any slot, it shows an error message instead.
A switch works the same way. It takes one value, jumps to the case that matches it, and runs that code. If nothing matches, it runs the default code.
The arrow form
Modern Java (version 14 and newer) has a clean arrow form of switch. Here's the day-of-the-week example again:
int day = 3;
switch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
case 4 -> System.out.println("Thursday");
case 5 -> System.out.println("Friday");
default -> System.out.println("Weekend");
}switch (day)names the value to match.- Each
casegives one possible value, then->, then what to do. defaulthandles everything that didn't match. It works like the finalelse.
Only the matching case runs. With day set to 3, this prints Wednesday and nothing else.
Several values, one case
Separate values with commas when they should all do the same thing:
int day = 6;
switch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("School day");
case 6, 7 -> System.out.println("Weekend");
default -> System.out.println("That's not a day of the week");
}More than one line per case
If a case needs several statements, wrap them in curly braces:
char grade = 'B';
switch (grade) {
case 'A' -> {
System.out.println("Excellent!");
System.out.println("You made the honor roll.");
}
case 'B', 'C' -> System.out.println("Good work.");
default -> System.out.println("Let's review together.");
}What you can switch on
A switch can match:
- whole numbers:
int,short,byte(andchar, which is a number underneath) Stringvalues- enums, a special type for a fixed set of choices that you'll meet in later Java study
It can't match double, float, long, or boolean values. It also can't check ranges like score >= 90. Each case is an exact value. For ranges, stick with if and else if.
Switching on text is handy for menus and commands:
String command = "save";
switch (command) {
case "save" -> System.out.println("Saving your work...");
case "open" -> System.out.println("Opening a file...");
case "quit" -> System.out.println("Goodbye!");
default -> System.out.println("Unknown command: " + command);
}A switch on a String compares with equals for you, so the == problem from Working with Strings doesn't apply here. It is case-sensitive, though: "Save" would not match "save".
A switch that gives back a value
Often you use a switch just to pick a value. The arrow form can hand that value straight back, which makes it a switch expression:
int month = 2;
int days = switch (month) {
case 2 -> 28;
case 4, 6, 9, 11 -> 30;
default -> 31;
};
System.out.println("Days in month " + month + ": " + days); // 28Notice the semicolon after the closing brace: the whole switch is now one big value being stored in days, so the statement needs to end.
A switch expression must cover every possible value, so it almost always needs a default. Leave it out, and the compiler stops you, because it can't be sure days will get a value.
The older form, and the break trap
You'll see a different style of switch in older code, textbooks, and exam questions. It uses colons and break:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Some other day");
}break means "jump out of the switch now." And here's the trap: if you forget it, Java doesn't stop at the end of the matching case. It falls through and keeps running the next cases' code too, without checking their values:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
default:
System.out.println("Some other day");
}This prints:
Tuesday
Wednesday
Some other dayIt's like a vending machine that drops your snack, and then every snack below it. Fall-through is almost never what you want, and forgetting a break is one of the most common switch bugs.
The arrow form never falls through. That's the main reason to prefer it in new code. Learn to read the colon form, because you'll meet it, but write the arrow form.
Try it
This program runs a tiny cafeteria menu. It uses a switch expression to look up a price and a switch statement to print a message. Predict what it prints.
Running Java here
Running Java right in the browser is coming to Syntaxia soon. On your own computer, save this program as Main.java and run it with java Main.java, or use your editor's Run button.
Check your prediction
2 x adobo = 130.0 pesos
It's Friday!
Free dessert with every meal."adobo" shares a case with "sinigang", so the price is 65.0, and 65.0 * 2 is 130.0. Day 5 matches its own case, which has two lines inside braces.
Try it yourself
- Change
itemto"pizza". What prints now, and which part of the code handles it? - Add
"halo-halo"to the menu for 45 pesos. - Change
dayOfWeekto 6 and to 1, and predict the output each time. Then add a case so Saturday (6) printsHalf-day menu.
Check your understanding
Up next
So far, every line in your program runs at most once. What if you want to print a line 100 times, or keep asking a question until the answer is right? That's the job of Loops: for, while, and do-while.
