Switch Expressions in Java

Learn Java switch expressions, arrow labels, yield, enum exhaustiveness, and how the Java 21 pattern-matching switch differs.

published: reading time: 10 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java switch expressions, arrow labels, yield, enum exhaustiveness, and how the Java 21 pattern-matching switch differs.

Switch Expressions in Java

Switch expressions let a switch produce a value. They were previewed in Java 12 and 13, then became a standard feature in Java 14 (JEP 361).

Introduction

Switch expressions were previewed in Java 12 and 13 and became standard in Java 14. They evaluate to a value, so you can return or assign the result directly. The arrow label form (case ... ->) avoids fall-through and works in switch statements as well as switch expressions. Traditional colon labels remain available and can fall through.

Every switch expression must be exhaustive. For an int, that usually means adding a default branch. For an enum, you can list every constant and omit default, allowing the compiler to flag a newly added constant when the code is recompiled. The Java 21 pattern-matching switch is a separate feature: it was previewed in Java 17–20 and became standard in Java 21 (JEP 441).

This post covers switch expressions, arrow labels, yield, enum exhaustiveness, and the Java 21 pattern-matching switch.

When to Use / Not to Use

Use switch expressions when:

  • Selecting from multiple discrete values based on a single expression
  • Mapping input to output values (functional style)
  • Replacing simple if-else-if chains with mutually exclusive cases
  • Working with enum-based branching

Do not use switch expressions when:

  • Conditions span ranges—use if-else with comparisons
  • Complex conditions involving multiple variables—use if-else
  • Only two branches—use simple if-else or ternary operator
  • Fall-through behavior is needed (use colon labels in a switch statement)

Diagram: Switch Expression Flow

flowchart TD
    A["switch (expression)"] --> B{"Match Case?"}
    B -->|case A| C["yield valueA"]
    B -->|case B| D["yield valueB"]
    B -->|case C| E["yield valueC"]
    B -->|default| F["yield defaultValue"]
    C --> G["Result = valueA"]
    D --> G
    E --> G
    F --> G
    G --> H["Continue"]

Code Snippet: Switch Statements and Expressions

public class SwitchExpressionDemo {

    // Traditional switch statement with colon labels
    public static String getDayTypeOld(int day) {
        String result;
        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                result = "Weekday";
                break;
            case 6:
            case 7:
                result = "Weekend";
                break;
            default:
                result = "Invalid";
        }
        return result;
    }

    // Switch expression (standard since Java 14)
    public static String getDayTypeNew(int day) {
        return switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Invalid";
        };
    }

    // Switch expression with blocks (using yield)
    public static String getDayDescription(int day) {
        return switch (day) {
            case 1, 2, 3, 4, 5 -> {
                String desc = "Work day";
                yield desc + " (Monday-Friday)";
            }
            case 6 -> "Saturday - rest day";
            case 7 -> "Sunday - rest day";
            default -> throw new IllegalArgumentException("day must be between 1 and 7: " + day);
        };
    }

    // Pattern matching for switch (standard since Java 21)
    public static String describe(Object obj) {
        return switch (obj) {
            case Integer i when i > 0 -> "Positive integer: " + i;
            case Integer i -> "Non-positive integer: " + i;
            case String s -> "String of length " + s.length();
            case null -> "Null value";
            default -> "Something else: " + obj.getClass().getSimpleName();
        };
    }

    enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

    // No default is needed when every enum constant is covered.
    public static int lettersInDay(Day day) {
        return switch (day) {
            case MONDAY, FRIDAY, SUNDAY -> 6;
            case TUESDAY -> 7;
            case THURSDAY, SATURDAY -> 8;
            case WEDNESDAY -> 9;
        };
    }

    public static void main(String[] args) {
        // Basic usage
        System.out.println(getDayTypeNew(3)); // Weekday
        System.out.println(getDayTypeNew(7)); // Weekend
        System.out.println(lettersInDay(Day.WEDNESDAY)); // 9
        try {
            getDayDescription(8);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage()); // day must be between 1 and 7: 8
        }

        // Pattern matching examples
        System.out.println(describe(42));        // Positive integer: 42
        System.out.println(describe(-5));         // Non-positive integer: -5
        System.out.println(describe("hello"));   // String of length 5
        System.out.println(describe(null));      // Null value
        System.out.println(describe(3.14));      // Something else: Double
    }
}

Exhaustiveness and Invalid Input

Switch expressions have to produce a value on every path. A switch over an arbitrary int therefore needs a default or cases covering every possible value, which is impractical; decide explicitly how out-of-range input should behave. The getDayDescription example throws IllegalArgumentException for values outside 1–7.

An enum expression can omit default when all declared constants are listed. If a new constant is added, recompiling the switch can reveal the missing case. A default branch in this situation can hide that useful compiler warning. Classic switch statements do not generally have the same exhaustiveness requirement and can do nothing when no label matches.

For a block-bodied switch-expression rule, use yield to provide its value. A switch expression cannot complete normally without a value; it can instead throw an exception.

Trade-off Table

Feature Switch Statement Switch Expression
Returns value No Yes
Arrow labels Yes, standard since Java 14 Yes, standard since Java 14
Block value No yield yield provides a value from a block
Patterns Java 21; previewed in Java 17–20 Java 21; previewed in Java 17–20
Exhaustiveness Not generally required Required; enum cases may omit default when all constants are listed
Fall-through Possible with : labels; arrows do not fall through Possible with : labels; arrows do not fall through

Observability Checklist

  • Log switch input values and matched cases for debugging
  • Add metrics for case frequency distribution
  • Instrument default case hits (may indicate unexpected input)
  • Add integration tests for all case branches
  • Monitor for unhandled case patterns in production

Security Notes

  • Input validation: An int switch does not validate a domain such as 1–7 by itself; give invalid values an explicit result or throw an exception.
  • Enum safety: Cover every enum constant and omit default when you want recompilation to identify newly added constants.
  • Null handling: Before Java 21, a null selector throws NullPointerException. In a Java 21 pattern-matching switch, use case null when null should be handled explicitly.

Pitfalls

  1. Forgetting yield: A block in a switch expression needs to yield a value or throw.
  2. Adding default to every enum expression: When all constants are already covered, omitting it can expose newly added constants on recompilation.
  3. Mixing : and -> labels: A switch block uses one label style, not both.
  4. Assuming every switch statement is exhaustive: A classic statement can silently do nothing when no label matches.
  5. Assuming case null works in Java 14: It became available with Java 21’s pattern-matching switch; earlier switch selectors throw NullPointerException for null.

Quick Recap

  • Switch expressions became standard in Java 14; arrow labels also work in switch statements.
  • Use yield to provide a value from a block in a switch expression.
  • Multiple values can be comma-separated in one case: case 1, 2, 3 ->
  • Switch expressions must be exhaustive. An enum expression can omit default when every constant is listed.
  • Pattern matching and case null in switch became standard in Java 21.

Interview Questions

1. What is the difference between a switch statement and a switch expression?
A switch statement executes a branch for its side effects. A switch expression produces a value that you can return, assign, or pass to a method. Both forms support arrow labels; only a switch expression uses `yield` to provide a value from a block.
2. What does `yield` do?
`yield value` provides the result of a block-bodied case in a switch expression. It does not return from the enclosing method; `return` does.
3. Can a switch expression stand alone as a statement?
No. A switch expression produces a value, so use it in a context such as an assignment, return, or method argument. Use a switch statement when the branches perform actions without producing a result.
4. How do colon and arrow labels differ?
Colon labels can fall through unless control leaves the switch, often with `break`. Arrow labels do not fall through and work in both switch statements and expressions. A switch block cannot mix the two label styles.
5. Does every enum switch expression need `default`?
No. If the expression lists every enum constant, it is exhaustive without `default`. When the enum later gains a constant, recompiling the switch can expose the missing case. A `default` can hide that compile-time signal.
6. Does a switch expression over `int` need `default`?
Usually, yes. An `int` can have any value, so list every possible value only when the domain is truly bounded by the type. Otherwise, use `default` to return an explicit fallback or throw for invalid input.
7. When did pattern matching for switch become standard?
Pattern matching for switch became standard in Java 21 after preview releases in Java 17 through Java 20. It is separate from switch expressions, which became standard in Java 14.
8. How does switch handle a null selector?
Before Java 21, a null selector throws `NullPointerException`. Java 21 switch patterns allow an explicit `case null` in statements and expressions.
9. How can a switch over a sealed hierarchy be exhaustive?
With Java 21 pattern matching, cover every permitted subtype in the switch. If the cases cover the sealed hierarchy, the expression can omit `default`, and the compiler checks the coverage.
10. Can `break` provide a switch-expression value?
No. Use `yield` to provide the value from a block case. In a switch statement, `break` exits the switch and prevents colon-label fall-through.
## Further Reading

Conclusion

Switch expressions modernize Java’s branching by treating switch as an expression that returns values rather than just a statement that executes code. The arrow syntax -> and yield keyword eliminate the traditional fall-through bug, and exhaustive checking at compile time prevents runtime surprises.

Pattern matching in switch (Java 21+) takes this further by matching on types directly, eliminating chains of instanceof checks. For most multi-way branching scenarios, switch expressions are cleaner than if-else chains and more maintainable than scattered conditionals.

Switch expressions became standard in Java 14. Arrow labels can also simplify switch statements, while pattern matching and case null arrived later as part of Java 21. For enum expressions, listing every constant without default leaves the compiler able to flag a missing case after the enum changes. Use a default for open-ended inputs such as arbitrary integers, and decide explicitly how invalid values should behave.

The ternary operator remains useful for simple binary choices, while if-else statements handle ranges and complex conditions.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals