Switch Expressions
Java's arrow switch never falls through, lets one case match several values, and can give back a value you store in a variable, with no break to forget.
Apprentice · Java · Updated
After this lesson you can
- Explain fall-through, and why an arrow case never falls through
- Choose a value with a Java switch expression, using arrow cases, commas and default
Key takeaways
- In a
case "book":switch, a case with nobreakfalls through and runs the next case's code too. An arrow case (->) runs only its own code, so it never falls through. - One arrow case can match several values, separated by commas:
case "Saturday", "Sunday" ->. Read the comma as "or". - A switch expression gives back a value you can store:
String ribbon = switch (giftType) { ... };, with a semicolon after the closing brace. - A switch expression needs a result for every possible value, so a switch expression on a
Stringor anintneeds adefault. - A case that needs more than one line gets a block in braces and hands its value back with
yield.
The switch from the last lesson, Switch, does its job, but it asks a lot of you: a break at the end of every case, and, when the switch is there to pick a value, a variable declared up front and set in every case. Forget one break and the program quietly runs the wrong code, with no error to warn you.
Since Java 14, switch has a second form that fixes both problems. It's the form you'll see in most Java code written today, and IntelliJ IDEA even offers to rewrite an older switch this way. You'll use it whenever one value decides another: an order's status decides the message a customer sees, a shirt size decides its price, a kind of gift decides the color of its ribbon.
The trouble with case and break
Picture a cafeteria line. You ask for the soup, the server puts soup on your tray, and then keeps going down the line, adding the salad, the pasta and the pie, until you say "stop". That's how the switch from the last lesson behaves. Java jumps to the case that matches, runs its code, and then keeps running the code of every case below it until it reaches a break. This is called fall-through: the program falls through from one case into the next.
Here a gift shop picks a ribbon color for each kind of gift. The "book" case is missing its break:
String giftType = "book";
String ribbon = "";
switch (giftType) {
case "book":
ribbon = "red";
case "puzzle":
ribbon = "blue";
break;
default:
ribbon = "white";
break;
}
System.out.println(ribbon);
blue
The book was meant to get a red ribbon. Java matched "book" and set ribbon to "red", then fell through into the "puzzle" case and set it to "blue". Only then did it reach a break. The code compiles and runs without a single warning; the only sign of the mistake is the wrong answer.
Here is the same switch written correctly, with one more kind of gift:
String giftType = "socks";
String ribbon = "";
switch (giftType) {
case "book":
ribbon = "red";
break;
case "puzzle":
ribbon = "blue";
break;
case "candle":
case "socks":
ribbon = "gold";
break;
default:
ribbon = "white";
break;
}
System.out.println(ribbon + " ribbon");
gold ribbon
It works, but look at what it took:
- A
breakin every case. Each one is a chance to forget it. - A variable declared before the switch, with a placeholder value (
""), then set again in every case. Leave out one of those lines andribbonkeeps its placeholder, and again there's no error. - Fall-through on purpose.
case "candle":has no code and nobreak, so it falls through intocase "socks":. That's how the old form lets two values share one result, and it looks exactly like the mistake in the first example.
Fifteen lines of switch hold one small decision: four kinds of gift and four ribbon colors.
The arrow form: case ->
The newer form replaces the colon with an arrow, ->, a hyphen followed by a greater-than sign. Read case "book" -> aloud as "case book, arrow", or more naturally, "in the case of book, do this". Here is the restaurant example from the last lesson, written with arrows:
String dayOfTheWeek = "Wednesday";
switch (dayOfTheWeek) {
case "Monday" -> System.out.println("Let's eat at Joe's Diner.");
case "Tuesday" -> System.out.println("How about Taco Tuesday at El Mexicano?");
case "Wednesday" -> System.out.println("Mid-week sushi at Sakura Sushi!");
case "Thursday" -> System.out.println("Try the pasta at Bella Italia.");
case "Friday" -> System.out.println("Relax with burgers at Burger Barn.");
default -> System.out.println("It's the weekend! Explore new places!");
}
Mid-week sushi at Sakura Sushi!
There's no break anywhere, and none is needed: an arrow case never falls through. Java runs the code on the right of the matching arrow, and then the switch is over. Back in the cafeteria, the server puts the soup on your tray and hands it over. Nothing else gets added.
A few things to know about the arrow form:
default ->works the same way as before: it runs when no case matches.- One switch uses one kind of case. Mixing
case "Monday":andcase "Tuesday" ->in the same switch doesn't compile; Java reports different case kinds used in the switch. - The switch compares values the way
.equals()does from Multiple Conditions: exactly, capital letters included."Wednesday"matchescase "Wednesday", but"wednesday"doesn't. - Some books and IntelliJ IDEA call this form the enhanced switch. The Java language rules call each arrow line a switch rule. They all mean the same thing.
Several values in one case
A store keeps the same hours Monday through Friday, shorter hours on Saturday, and shorter still on Sunday. Five days share one answer. In the arrow form, you list the values in one case, separated by commas. Read the comma as "or": case "Saturday", "Sunday" is "case Saturday or Sunday".
String dayOfTheWeek = "Saturday";
switch (dayOfTheWeek) {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> System.out.println("Open 9 AM to 9 PM");
case "Saturday" -> System.out.println("Open 10 AM to 6 PM");
case "Sunday" -> System.out.println("Open noon to 5 PM");
default -> System.out.println("That isn't a day of the week.");
}
Open 10 AM to 6 PM
This replaces the old trick of stacking case "candle": case "socks": and letting one fall through into the other. The commas say plainly that these values share a result, and nothing falls anywhere.
A switch that gives back a value
Everything so far is a switch statement: it does something, such as printing a line. Much of the time, though, a switch exists to pick something: the ribbon, the price, the message. Java's arrow switch can hand that value straight back, so you can store it in a variable. This is a switch expression.
An expression is any piece of code that produces a value. 2 + 3 is an expression that produces 5; price * quantity produces a total. A statement is a complete instruction that does something, such as System.out.println("Hi");. A switch expression is a whole switch that produces one value, so it can sit on the right of an =, like any other value.
Here is the gift shop's ribbon, as a switch expression:
String giftType = "candle";
String ribbon = switch (giftType) {
case "book" -> "red";
case "puzzle" -> "blue";
case "candle", "socks" -> "gold";
default -> "white";
};
System.out.println(ribbon + " ribbon");
gold ribbon
Read the first case aloud as "case book gives red". Compare it with the fifteen-line version above:
- No placeholder.
ribbonis declared and given its value in one statement: whatever the switch gives back. - No repeated
ribbon =. Each case says only its result, on the right of the arrow. - No
break. An arrow case never falls through. - A semicolon after the closing brace:
};. People often leave it out at first. The line is one statement,String ribbon = ...;, the same shape asString ribbon = "red";. The switch is the value in the middle, and the semicolon ends the whole statement.
A switch expression also fits right after return, when a method's whole job is to turn one value into another. This method gives the number of days an order takes to arrive:
int shippingDays(String shippingSpeed)
{
return switch (shippingSpeed) {
case "overnight" -> 1;
case "express" -> 2;
default -> 5;
};
}
shippingDays("express") returns 2, and any other speed, such as "standard", returns 5.
Rules a switch expression must follow
Because a switch expression always has to produce a value, Java holds it to two rules that a switch statement doesn't have. The compiler checks both before your program runs, which turns the silent mistakes of the old form into errors you can see and fix.
Every possible value needs a result. A String could hold any text at all, so no list of cases can name them all. A switch expression on a String or an int therefore needs a default. Leave it out and the program doesn't compile. Java points at the switch and says:
error: the switch expression does not cover all possible input values
That's the variable-left-unset problem from the old form, caught for you: there's no way for a value to slip through without a result.
Every result must fit the variable. ribbon is a String, so every case must give back a String. A case such as case "puzzle" -> 2; stops the program compiling with incompatible types: bad type in switch expression, because 2 is a number, not text.
When a case needs more than one line
Usually, each case gives back a single value. Sometimes one case has to work its result out first. An online store charges $12 for express shipping and $25 for overnight. Standard shipping, the default, costs $5, but it's free on orders of $50 or more. The standard case has its own decision to make.
For that, the case gets a block: braces with as many lines as it needs. Inside a block, yield hands the case's value back to the switch. The word means "give up" or "hand over", the way a field yields a crop.
int shippingCost(String shippingSpeed, int orderTotal)
{
return switch (shippingSpeed) {
case "express" -> 12;
case "overnight" -> 25;
default -> {
if (orderTotal >= 50)
{
yield 0;
}
yield 5;
}
};
}
shippingCost("standard", 62) returns 0: the speed isn't express or overnight, so the default case runs, the order comes to $62, the if is true, and the case yields 0. shippingCost("standard", 30) returns 5: the if is false, so the case reaches yield 5; instead. shippingCost("express", 62) returns 12, whatever the total.
yieldis only for blocks inside a switch expression. A one-line case likecase "express" -> 12;hands back its value without it.yieldisn'treturn.returnwould end the whole method;yieldends only the switch, with its value.- Every way out of the block must reach a
yield. If theifwere false and there were noyield 5;, Java would refuse to compile, with switch rule completes without providing a value.
Reach for a block only when a case truly needs it. When most of your cases need several lines, a switch statement or an if usually reads better.
Switch or if-else if?
Here is the gift shop's ribbon once more, written with if-else if-else from the If lesson:
String giftType = "candle";
String ribbon;
if (giftType.equals("book")) {
ribbon = "red";
} else if (giftType.equals("puzzle")) {
ribbon = "blue";
} else if (giftType.equals("candle") || giftType.equals("socks")) {
ribbon = "gold";
} else {
ribbon = "white";
}
System.out.println(ribbon + " ribbon");
gold ribbon
It gives the same answer, but giftType.equals(...) repeats on every line, and ribbon = repeats in every branch. When one variable is compared against a list of exact values, the switch expression says it more plainly.
An if can do things a switch can't, though. A switch matches exact values of one variable: "book", "Saturday", 3. It can't ask "is the order $50 or more?", and it can't look at two variables at once. Those questions belong to if, as in the shipping example, where an if sits inside the switch's default case.
| You want to | Use |
|---|---|
Run different code depending on a range or on several variables (orderTotal >= 50) |
if / else if / else |
| Run different code for each exact value of one variable | a switch statement with arrow cases |
| Pick a value for each exact value of one variable | a switch expression |
A switch works on Strings, whole numbers such as int, and single characters (char). A double or a boolean can't be switched on: a price like 19.99 or a true/false question goes to an if.
Do it: show the gym's class for the day
A neighborhood gym runs one group class a day, and its front-desk screen needs to show the class for any day of the week.
The function gets one value:
dayOfTheWeek: the day's name, aStringwith a capital first letter ("Wednesday").
The classes:
| Day | Class |
|---|---|
"Monday", "Wednesday" or "Friday" |
"Spin" |
"Tuesday" or "Thursday" |
"Yoga" |
"Saturday" |
"Open swim" |
| any other day | "Closed" |
For example, "Wednesday" is one of the three Spin days, so classForDay("Wednesday") returns "Spin".
Your job: finish the function String classForDay(String dayOfTheWeek) so it returns the class from the table, with a switch expression after return.
- Days that share a class share one arrow case, their names separated by commas.
- Any other value, such as
"Sunday", gives"Closed". - The
return switchline and the closing};are already there.
Practiced live on the lesson page: write the Java right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
With arrow cases there's no break to forget and nothing falls through, and a switch expression hands its value straight to your variable, so the compiler, not a customer, finds the case you missed.