Switch Expressions
Most switches exist to work out a value: the name of a day, the fare for a coach class, a discount for a coupon. The old switch makes you declare a variable, assign it in every case, and remember a break each time. Since Java 14, a switch can be an expression: it produces a value directly, in a fraction of the code, with no fall-through to forget.
Old vs New
public class Fare {
public static void main(String[] args) {
String coach = "AC3";
int fare = switch (coach) {
case "SL" -> 450;
case "AC3" -> 1180;
case "AC2" -> 1690;
default -> 0;
};
System.out.println("Fare: Rs. " + fare);
}
}public class FareOld {
public static void main(String[] args) {
String coach = "AC3";
int fare;
switch (coach) {
case "SL":
fare = 450;
break;
case "AC3":
fare = 1180;
break;
case "AC2":
fare = 1690;
break;
default:
fare = 0;
}
System.out.println("Fare: Rs. " + fare);
}
}Fare: Rs. 1180How it works
- Line 4:
switch (coach)is now on the right-hand side of=. The whole switch evaluates to one value, which goes intofare. - Each
case ... ->gives the value for that case. There's nobreakand no fall-through. - Line 9 ends with
;, because the switch expression is part of an assignment statement.
Try it yourself: set coach to "CC" and run it. Then remove the default line. What does the compiler say?
Several Labels, and Blocks with yield
One case can list several values. When a case needs more than one line, use a block { } and hand back the value with yield:
public class Coupon {
public static void main(String[] args) {
int day = 6;
String offer = switch (day) {
case 1, 2, 3, 4, 5 -> "5% off on weekdays";
case 6, 7 -> {
int percent = 15;
if (day == 7) {
percent = 20;
}
yield percent + "% off this weekend";
}
default -> "Invalid day";
};
System.out.println(offer);
}
}15% off this weekendyield is like return, but for one case of a switch expression: it gives that case's value and leaves the switch. It's a contextual keyword, so it's only special here.
Every Input Must Be Covered
A switch expression must produce a value for every possible input. With an int or a String, that means you need default:
SwExpr.java:4: error: the switch expression does not cover all possible input values
String name = switch (day) {
^With an enum, listing every constant is enough, and no default is needed. If someone later adds a new constant, the compiler points to every switch that forgot it. This check is called exhaustiveness, and it's one of the biggest advantages of switch expressions.
Common Mistakes
Forgetting the semicolon after the closing brace. int fare = switch (...) { ... } needs ; at the end, like any assignment.
Using return instead of yield inside a case block. return would try to leave the whole method; inside a switch expression it doesn't compile. Use yield.
Mixing : and -> in the same switch. A switch uses one style or the other, not both.
Practice
- Easy: Rewrite the month-name switch from the previous lesson as a switch expression that returns the name.
- Harder: Write a switch expression that returns the GST rate (0, 5, 12, 18 or 28) for these items:
"milk","tea","butter","soap","car". Use a block withyieldfor one of them, and print the tax on Rs. 1000.
Key Takeaways
Was this tutorial helpful?