Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 18 - Modern Java Features 8 to 21

Java 12 Switch Expression with Arrow Syntax and Yield

Reviewed & accurate
AI Summary

Introduction

Java 12, released in March 2019, introduced switch expressions as a preview feature under JEP 325. The classical switch statement in Java had been unchanged since Java 1.0 in 1996: it was a flow-control construct that fell through cases unless you remembered to write break, and it could not return a value. Java 12 switch expression fixed both shortcomings by introducing arrow-style case labels with no fall-through and by allowing the entire switch to be used as an expression that yields a value. Java 13 refined the feature with a new yield statement to return a value from a multi-line block, and Java 14 finalised switch expressions as a standard language feature under JEP 361.

For a Java learner, java 12 switch expression is the modern replacement for chained if-else-if ladders and for the classical switch statement when mapping a small set of constants. It produces shorter code, eliminates the fall-through bug class, and integrates cleanly with the Stream API and record patterns. This post walks through the arrow syntax, the yield statement, exhaustive enum switching, and the rules that distinguish the new expression form from the older statement form.

What is Java 12 Switch Expression?

A switch expression is a switch that produces a value. It uses arrow-style case labels written as case L -> instead of the classical case L: followed by statements and break. The arrow form has two crucial properties: there is no fall-through, so each arm runs only its own block, and the right-hand side of the arrow can be a single expression, a throw statement, or a brace-delimited block that uses yield to return a value.

Conceptually, the switch expression belongs to the family of expression-oriented control-flow constructs, alongside the ternary operator (cond ? a : b) and the new pattern-matching switch added in Java 21. Unlike the ternary operator, switch can branch on multiple constants, not just on a boolean. Unlike the older switch statement, the expression form must yield a value (or throw) on every path, so the compiler enforces exhaustiveness when you switch on an enum.

How Java 12 Switch Expression Works - Step by Step

Step 1: Pick a selector expression. The value inside switch (...) can be an int, Integer, byte, Byte, short, Short, char, Character, String (since Java 7), or any enum. Java 21 extends the selector to allow any object reference and to perform pattern matching, but Java 12 only accepts the classical types.

Step 2: Write each arm with the arrow label. The label form is case L -> where L is a constant. You can list multiple constants on one label separated by commas: case 1, 2, 3 ->. The right-hand side of the arrow can be a single expression like "small", a method call like compute(), a throw statement like throw new IllegalArgumentException(), or a brace block.

Step 3: Yield from a brace block. When the arm needs multiple statements, write a brace block ending with yield value;. The yield keyword was added in Java 13 to replace the older break value; form that Java 12 preview used. In Java 14 and later, yield is the only legal way to return a value from a multi-line arm.

Step 4: Handle the default case. If you switch on an enum and list every enum constant, you do not need a default arm; the compiler knows the switch is exhaustive. If you omit a constant and have no default, the compiler will reject the switch as non-exhaustive. For int and String switches, you must always supply a default or list every possible constant, which is rarely practical.

Step 5: Use the value. Because switch is now an expression, you can assign it to a variable, return it from a method, or use it inline in another expression. For example, String size = switch (n) { case 1, 2, 3 -> "small"; ... }; assigns the result of the switch expression to the size variable.

Java Program for Switch Expression

import java.util.DayOfWeek;
import java.time.LocalDate;

public class SwitchExpressionDemo {

    enum TrafficLight { RED, YELLOW, GREEN }

    // (1) Arrow form with multiple constants on one label
    static String classify(int n) {
        return switch (n) {
            case 0 -> "zero";
            case 1, 2, 3 -> "small";
            case 4, 5, 6, 7, 8, 9 -> "medium";
            default -> "large";
        };
    }

    // (2) Switching on an enum exhaustively, no default needed
    static String action(TrafficLight light) {
        return switch (light) {
            case RED -> "stop";
            case YELLOW -> "caution";
            case GREEN -> "go";
        };
    }

    // (3) Multi-line arm using yield
    static int daysInMonth(int year, int month) {
        return switch (month) {
            case 1, 3, 5, 7, 8, 10, 12 -> 31;
            case 4, 6, 9, 11 -> 30;
            case 2 -> {
                boolean leap = (year % 4 == 0 && year % 100 != 0)
                        || (year % 400 == 0);
                yield leap ? 29 : 28;
            }
            default -> {
                System.out.println("invalid month " + month);
                yield -1;
            }
        };
    }

    // (4) Throw from an arm
    static String requireKnown(String name) {
        return switch (name) {
            case "admin", "root" -> "superuser";
            case "guest" -> "anonymous";
            default -> throw new IllegalArgumentException(
                    "unknown user: " + name);
        };
    }

    // (5) Switch as inline argument to println
    static void printSeason(DayOfWeek d) {
        String mood = switch (d) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "work";
            case SATURDAY, SUNDAY -> "rest";
        };
        System.out.println(d + " -> " + mood);
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 12; i++) {
            System.out.println(i + " is " + classify(i));
        }
        System.out.println("---");
        for (TrafficLight t : TrafficLight.values()) {
            System.out.println(t + " -> " + action(t));
        }
        System.out.println("---");
        System.out.println("Feb 2024 days: " + daysInMonth(2024, 2));
        System.out.println("Feb 2023 days: " + daysInMonth(2023, 2));
        System.out.println("Apr 2024 days: " + daysInMonth(2024, 4));
        System.out.println("---");
        System.out.println("admin -> " + requireKnown("admin"));
        System.out.println("guest -> " + requireKnown("guest"));
        try {
            requireKnown("hacker");
        } catch (IllegalArgumentException e) {
            System.out.println("threw: " + e.getMessage());
        }
        System.out.println("---");
        DayOfWeek today = LocalDate.now().getDayOfWeek();
        printSeason(today);
        for (DayOfWeek d : DayOfWeek.values()) {
            printSeason(d);
        }
    }
}

Code Explanation - Line by Line

Method (1) classify is the simplest switch expression: each arm is a single string literal on the right of the arrow. The first arm matches only zero, the second matches 1, 2, or 3, the third matches 4 through 9, and the default catches 10 and above. Because every arm is a single expression, no braces or yield are needed; the value of the arm is the value of the expression.

Method (2) action switches on a TrafficLight enum exhaustively. The three arms cover RED, YELLOW, and GREEN, so no default is required. If you later added a fourth enum constant (say FLASHING) without updating the switch, the compiler would emit an error: "the switch expression does not cover all possible input values". This exhaustiveness check is one of the biggest safety wins of switch expressions over the older switch statement, which would silently fall through to no-op when a new enum constant was added.

Method (3) daysInMonth demonstrates the multi-line arm with yield. The case for February has a brace block that computes the leap-year predicate as a local boolean, then yields 29 if the year is a leap year and 28 otherwise. The yield keyword is the only way to return a value from a brace block in a switch expression; using return would exit the enclosing method rather than the switch. The default arm also uses yield after logging the invalid month, returning -1 as a sentinel error value.

Method (4) requireKnown shows that an arm can throw instead of yield a value. The default case throws IllegalArgumentException, which the JVM treats as completing the switch abruptly. Because throw is a statement that does not produce a value, no yield is needed.

Method (5) printSeason embeds the switch expression directly in an assignment statement. The variable mood takes the value of the switch expression. The same pattern can be used as a method argument or as the right-hand side of a return statement, which is impossible with the classical switch statement because that statement has no value.

Sample Input and Output

Input:  args = [] (uses fixed demo data)
Output:
0 is zero
1 is small
2 is small
3 is small
4 is medium
5 is medium
6 is medium
7 is medium
8 is medium
9 is medium
10 is large
11 is large
12 is large
---
RED -> stop
YELLOW -> caution
GREEN -> go
---
Feb 2024 days: 29
Feb 2023 days: 28
Apr 2024 days: 30
---
admin -> superuser
guest -> anonymous
threw: unknown user: hacker
---
MONDAY -> work
TUESDAY -> work
WEDNESDAY -> work
THURSDAY -> work
FRIDAY -> work
SATURDAY -> rest
SUNDAY -> rest

The output confirms that the switch expression returns the right arm value for every input, that April's arm correctly returns 30 days, that February correctly returns 29 for the leap year 2024 and 28 for the non-leap year 2023, and that the default arm in requireKnown throws IllegalArgumentException when given an unknown user name.

Common Mistakes to Avoid

The first mistake is forgetting that arrow labels do not fall through. Programmers who learned the classical switch statement sometimes add a break statement at the end of an arrow arm, which the compiler rejects with "unexpected token break". The arrow form runs only the block on the right of the arrow; no break is needed.

The second mistake is mixing the arrow label with the colon label in the same switch. The compiler requires that every case in a switch expression use the same form: either all arrows or all colons with break. Mixing the two yields a compile-time error.

The third mistake is forgetting yield inside a brace block. Without a yield, the block runs but the switch has no value to return, and the compiler reports "missing return value". Some developers write return value instead, but that exits the enclosing method, not the switch, and produces wrong runtime behaviour.

The fourth mistake is omitting the default arm when switching on an int or String. The compiler does not enforce exhaustiveness for non-enum switches, but at runtime a missing match means the switch expression returns no value, which is illegal. Always supply a default arm or, for enums, make sure every constant is listed.

Real-World Applications

In production Java code, switch expressions are heavily used in mapping layers: HTTP status codes to user-facing messages, enum kinds to handler strategies, and ISO country codes to locale defaults. Spring Framework's PropertyPlaceholderHelper and Spring Boot's auto-configuration code use switch expressions to dispatch on enum values cleanly without the break-heavy classical form. The Jackson JSON library's internal token dispatcher uses switch expressions on its JsonToken enum to keep the parsing code compact.

In build tools and developer tooling, the Gradle build tool's Kotlin and Groovy DSLs compile to switch expressions when the input is an enum, taking advantage of the exhaustiveness check so that adding a new enum constant forces the developer to update every switch. The Maven build tool's lifecycle phase dispatcher uses switch expressions on LifecyclePhase to map phase names to the underlying goal list.

In test frameworks, JUnit 5's invocation interceptor chain uses switch expressions to dispatch on the InvocationInterceptor.InvocationKind enum, making the chain readable. The TestNG framework's parameter resolver uses switch expressions on ParameterKind to keep its argument-binding code compact and exhaustive-checked.

Conclusion

Java 12 switch expression (finalised in Java 14) brings the older switch statement into the expression-oriented world by introducing arrow labels with no fall-through and the yield keyword for multi-line arms. The feature eliminates the most common source of bugs in classical switch code (the missing break) and adds compile-time exhaustiveness checking for enum switches. Next, study Java 14 records for the natural data-carrier pairing with switch expressions, and then move on to Java 21 pattern matching for switch, which extends the switch expression to destructure objects of arbitrary types.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments