Switch Expressions

Naveen AnamaneniUpdated · 4 min read

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

Fare.java▶ Try it
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);
    }
}
Output
Fare: Rs. 1180

How it works

  1. Line 4: switch (coach) is now on the right-hand side of =. The whole switch evaluates to one value, which goes into fare.
  2. Each case ... -> gives the value for that case. There's no break and no fall-through.
  3. 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:

Coupon.java▶ Try it
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);
    }
}
Output
15% off this weekend

yield 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:

Compiler output
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

  1. Easy: Rewrite the month-name switch from the previous lesson as a switch expression that returns the name.
  2. 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 with yield for one of them, and print the tax on Rs. 1000.

Quick check: Switch expressions

4 questions
1What is the main difference between a switch expression and a switch statement?
2What does yield do?
3Why does a switch expression on an int usually need default?
4Does the arrow form fall through to the next case?

Key Takeaways

Was this tutorial helpful?

Lesson 56 of 482