Switch expressions

Since Java 14, switch can be an expression that produces a value, and cases can use an arrow that never falls through. Together they remove the two classic switch bugs, a forgotten break and a variable left unassigned in some case. Every example was run on JDK 25, including the bytecode javac produces for number, String and enum switches.

CsCode.ioUpdated
Share

Contents

Introduction

Java has had a switch statement since version 1.0. It runs the code for the matching case and produces no value, so code that needs a result assigns a variable in each case. That design has two well-known failure modes. A missing break lets execution fall into the next case, and a case that forgets the assignment leaves the variable unset.

Java 14 added two separate features that fix them:

  • Arrow cases, case 6, 7 -> ..., run only the code to the right of the arrow and never fall through. Several labels share a case when they are separated by commas.
  • Switch expressions produce a value, so they can appear on the right of =, as an argument or after return. An expression must be exhaustive, which means some case must apply to every possible value, so the result is always defined.

The two are independent. An arrow switch can be a statement, and an expression can use colon cases with yield. In practice, the arrow expression is the form to prefer.

What switch can do, by version
FeatureSinceBest for
int, char, short, byte selectorsJava 1.0Numeric codes
Enum selectorsJava 5States, kinds, modes
String selectorsJava 7Commands, keys, text codes
Arrow cases and switch expressionsJava 14, after previews in 12 and 13Computing a value with no fall-through
Patterns, case null, any reference typeJava 21Branching on type, see pattern matching for switch

In the Java 12 preview, a switch expression returned its value with break value, and Java 13 replaced that with yield. Every program below needs Java 21 or later, and the outputs shown come from JDK 25.

Arrow cases and the fall-through bug

Here is the classic bug. The weekend case is missing its break, so day 6 runs on into the code for case 1:

Java
public class FallThroughBug {
    @SuppressWarnings("fallthrough")       // the fall-through is the bug being shown
    static String kind(int day) {
        String kind = "unknown";
        switch (day) {
            case 6:
            case 7:
                kind = "weekend";
                // missing break: execution continues into case 1
            case 1:
                kind = "start of week";
                break;
            default:
                kind = "weekday";
        }
        return kind;
    }

    public static void main(String[] args) {
        System.out.println("day 1: " + kind(1) + ", day 3: " + kind(3) + ", day 6: " + kind(6));
    }
}

Running it prints:

Output
day 1: start of week, day 3: weekday, day 6: start of week

Day 6 came out as "start of week". The code set kind to "weekend", fell into case 1, overwrote it and only then reached a break. javac can warn about this with -Xlint:fallthrough, and the program turns that warning off with @SuppressWarnings because the bug is the point.

The same logic as an arrow switch expression cannot fall through:

Java
public class ArrowSwitch {
    static String kind(int day) {
        return switch (day) {
            case 6, 7 -> "weekend";               // several labels share one case
            case 1 -> "start of week";
            case 2, 3, 4, 5 -> "weekday";
            default -> throw new IllegalArgumentException("day " + day);
        };
    }

    public static void main(String[] args) {
        System.out.println("day 1: " + kind(1) + ", day 3: " + kind(3) + ", day 6: " + kind(6));
        try {
            kind(9);
        } catch (IllegalArgumentException e) {
            System.out.println("kind(9) threw: " + e.getMessage());
        }
    }
}

Running it prints:

Output
day 1: start of week, day 3: weekday, day 6: weekend
kind(9) threw: day 9

Day 6 is now "weekend". The second line shows that a case may throw instead of producing a value, even in an expression, so kind(9) threw with the message "day 9".

Blocks, yield and exhaustive enum switches

What if a case needs more than one expression? Put a block on the right of the arrow and end it with yield value. yield is to a switch expression what return is to a method, while return itself would try to leave the enclosing method. The example prices drinks by size, with an enum in its own file:

Java
public enum Size { SMALL, MEDIUM, LARGE }

Members get 50 cents off a medium and 10% off a large, so each size follows a different rule:

Java
public class YieldBlocks {
    static int priceCents(Size size, boolean member) {
        return switch (size) {
            case SMALL -> 250;
            case MEDIUM -> {
                int base = 350;
                yield member ? base - 50 : base;       // yield gives the block's value
            }
            case LARGE -> {
                int base = 450;
                yield member ? base - base / 10 : base;
            }
        };                                             // all three sizes listed: no default
    }

    public static void main(String[] args) {
        for (Size s : Size.values()) {
            System.out.println(s + ": regular " + priceCents(s, false)
                    + ", member " + priceCents(s, true));
        }
    }
}

Running it prints:

Output
SMALL: regular 250, member 250
MEDIUM: regular 350, member 300
LARGE: regular 450, member 405

Small has no member discount, medium is 350 - 50 = 300 cents, and large is 450 - 45 = 405. The switch lists all three sizes and has no default. If a size is added to the enum, priceCents stops compiling until the new size is handled. An enum switch statement has no such check.

yield also works with colon cases, where labels still fall through:

Java
public class ColonYield {
    static String status(int code) {
        return switch (code) {
            case 200:
                yield "OK";
            case 301:
            case 302:                // 301 falls through to here
                yield "redirect";
            default:
                yield "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(status(200) + ", " + status(301) + ", " + status(404));
    }
}

Running it prints:

Output
OK, redirect, other

Every path ends with yield, and 301 shares "redirect" with 302 by falling through. The arrow form, case 301, 302 ->, says the same thing more clearly.

Switching on strings

String switches work naturally with arrows. The next example is a tiny interpreter that applies commands to a running value. Each command is a record in its own file:

Java
// One step of a tiny program: a command name and its number
public record Command(String name, int arg) {
}

The command times shares a case with mul, and jump is unknown, so the default block prints a message before it yields the unchanged value:

Java
import java.util.List;

public class StringSwitch {
    static int apply(int value, Command c) {
        return switch (c.name()) {
            case "add" -> value + c.arg();
            case "sub" -> value - c.arg();
            case "mul", "times" -> value * c.arg();
            case "reset" -> 0;
            default -> {
                System.out.println("  ignoring unknown command '" + c.name() + "'");
                yield value;
            }
        };
    }

    public static void main(String[] args) {
        List<Command> program = List.of(new Command("add", 5), new Command("times", 3),
                new Command("jump", 1), new Command("sub", 4));
        int value = 0;
        for (Command c : program) {
            value = apply(value, c);
            System.out.println(c.name() + " " + c.arg() + " -> " + value);
        }
    }
}

Running it prints:

Output
add 5 -> 5
times 3 -> 15
  ignoring unknown command 'jump'
jump 1 -> 15
sub 4 -> 11

The value goes 0 + 5 = 5, then 5 × 3 = 15, stays 15 for the unknown command and ends at 15 - 4 = 11. String cases are compared with equals, so they are case-sensitive. For user input, switch on s.toLowerCase(Locale.ROOT). A null selector throws NullPointerException unless the switch has case null, which needs Java 21.

How javac compiles a switch

A switch expression compiles to the same bytecode as a switch statement. What does that bytecode look like? Start with two switches over numbers, one with close values and one with values far apart:

Java
public class NumberSwitches {
    static int dense(int n) {
        return switch (n) {
            case 1 -> 10;
            case 2 -> 20;
            case 3 -> 30;
            default -> 0;
        };
    }

    static int sparse(int n) {
        return switch (n) {
            case 1 -> 10;
            case 1000 -> 20;
            case 50000 -> 30;
            default -> 0;
        };
    }
}

Compiling it and running javap -c -p NumberSwitches shows the instructions:

Output
static int dense(int);
    Code:
         0: iload_0
         1: tableswitch   { // 1 to 3
                       1: 28
                       2: 33
                       3: 38
                 default: 43
            }
        28: bipush        10
        30: goto          44
        33: bipush        20
        35: goto          44
        38: bipush        30
        40: goto          44
        43: iconst_0
        44: ireturn

  static int sparse(int);
    Code:
         0: iload_0
         1: lookupswitch  { // 3
                       1: 36
                    1000: 41
                   50000: 46
                 default: 51
            }
        36: bipush        10
        38: goto          52
        41: bipush        20
        43: goto          52
        46: bipush        30
        48: goto          52
        51: iconst_0
        52: ireturn

The cases 1, 2 and 3 in dense became a tableswitch, a jump table indexed by the value, so finding the case is one array lookup however many cases there are. The cases 1, 1000 and 50000 in sparse became a lookupswitch, a sorted list of values that the JVM can search quickly. A jump table from 1 to 50,000 would waste space.

A string switch is more interesting. This one uses two strings with the same hash code:

Java
public class TextSwitch {
    static int text(String s) {
        return switch (s) {          // "Aa" and "BB" have the same hashCode(), 2112
            case "Aa" -> 1;
            case "BB" -> 2;
            default -> 0;
        };
    }
}

Its bytecode:

Output
static int text(java.lang.String);
    Code:
         0: aload_0
         1: astore_1
         2: iconst_m1
         3: istore_2
         4: aload_1
         5: invokevirtual #7                  // Method java/lang/String.hashCode:()I
         8: lookupswitch  { // 1
                    2112: 28
                 default: 53
            }
        28: aload_1
        29: ldc           #13                 // String BB
        31: invokevirtual #15                 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
        34: ifeq          42
        37: iconst_1
        38: istore_2
        39: goto          53
        42: aload_1
        43: ldc           #19                 // String Aa
        45: invokevirtual #15                 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
        48: ifeq          53
        51: iconst_0
        52: istore_2
        53: iload_2
        54: lookupswitch  { // 2
                       0: 80
                       1: 84
                 default: 88
            }
        80: iconst_1
        81: goto          89
        84: iconst_2
        85: goto          89
        88: iconst_0
        89: ireturn

It runs in three steps, as the picture shows:

switch (s) with s equal to BB goes to step 1, a switch on s.hashCode() where 2112 means Aa or BB; step 2, equals() finds which one and sets index 1; step 3, a switch on the index jumps to case BB.

At instruction 5 the code calls hashCode(), and the lookupswitch at 8 has only one entry, 2112, because "Aa" and "BB" have the same hash code. The two equals calls at 31 and 45 then decide which string it really is and store its index, 0 or 1. The second lookupswitch, at 54, jumps to the case for that index. So equal hash codes are handled correctly, and a string switch usually costs one hash code and one equals call.

Last, an enum switch. The enum is in its own file:

Java
public enum Color { RED, GREEN, BLUE }
Java
public class ColorSwitch {
    static int color(Color c) {
        return switch (c) {
            case RED -> 1;
            case GREEN -> 2;
            case BLUE -> 3;
        };
    }
}

Its bytecode:

Output
static int color(Color);
    Code:
         0: getstatic     #7                  // Field ColorSwitch$1.$SwitchMap$Color:[I
         3: aload_0
         4: invokevirtual #13                 // Method Color.ordinal:()I
         7: iaload
         8: tableswitch   { // 1 to 3
                       1: 46
                       2: 50
                       3: 54
                 default: 36
            }
        36: new           #19                 // class java/lang/MatchException
        39: dup
        40: aconst_null
        41: aconst_null
        42: invokespecial #21                 // Method java/lang/MatchException."<init>":(Ljava/lang/String;Ljava/lang/Throwable;)V
        45: athrow
        46: iconst_1
        47: goto          55
        50: iconst_2
        51: goto          55
        54: iconst_3
        55: ireturn

The code reads ColorSwitch$1.$SwitchMap$Color, an array that javac generated in a helper class, indexes it with ordinal() and switches on the result. The array is filled when the helper class is first used, so the switch stays correct if the enum's constants are reordered and Color is recompiled on its own. Instructions 36 to 45 are the hidden default of an exhaustive enum switch. If a constant shows up that did not exist at compile time, it throws MatchException.

The type of a switch expression, and an unboxing trap

A switch expression has a type, worked out from its arms, much like the conditional operator ? :. This program combines arms of different types. The selector is a fixed 1, so the first arm is always taken and only the typing differs:

Java
public class ArmTypes {
    public static void main(String[] args) {
        int k = 1;                                    // the first arm is always taken
        var a = switch (k) {
            case 1 -> 1;                              // int
            default -> 2.5;                           // double
        };
        var b = switch (k) {
            case 1 -> 42;                             // Integer
            default -> "none";                        // String
        };
        long c = switch (k) {
            case 1 -> 7;                              // each arm converted to long
            default -> 8L;
        };
        System.out.println("int and double arms: " + a);
        System.out.println("Integer and String arms: " + b + ", a " + b.getClass().getSimpleName());
        System.out.println("assigned to long: " + c);
    }
}

Running it prints:

Output
int and double arms: 1.0
Integer and String arms: 42, a Integer
assigned to long: 7

With int and double arms, the expression is a double, so the arm that produced 1 printed as 1.0, the same promotion as with ? :. With Integer and String arms, var gets their common supertype, and the value stayed an Integer. Assigned to a long, each arm is converted to the target type on its own, so 7 became 7L.

One combination throws. Here an arm returns an Integer from a map, and the result goes into an int:

Java
import java.util.Map;

public class UnboxingTrap {
    public static void main(String[] args) {
        Map<String, Integer> stock = Map.of("tea", 3);   // no "milk" in stock
        int count = switch ("milk") {
            case "tea", "milk" -> stock.get("milk");      // a null Integer
            default -> 0;
        };
        System.out.println("count " + count);
    }
}

Running it prints:

Output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
	at UnboxingTrap.main(UnboxingTrap.java:7)

stock.get("milk") returned null, and assigning it to an int unboxed it, which threw NullPointerException. The message names the culprit, the return value of Map.get. Use getOrDefault, or make the target an Integer.

Last, the selector itself. Is it evaluated once, or once per case?

Java
public class SelectorOnce {
    static int calls = 0;

    static int next() {
        return ++calls;
    }

    public static void main(String[] args) {
        String r = switch (next()) {
            case 1 -> "one";
            case 2 -> "two";
            default -> "many";
        };
        System.out.println("selector evaluated " + calls + " time, result " + r);
    }
}

Running it prints:

Output
selector evaluated 1 time, result one

The selector ran exactly once, before any case was compared, so a selector with side effects is safe.

What the compiler checks

Which mistakes does the compiler catch? Each row below is one method body, compiled with javac 25. It switches on a three-constant enum, Size, with the constants S, M and L, inside this class:

Java
class T {
    int n;

    void m(Size s) {
        // the body from the table goes here
    }
}
Method bodies and what javac 25 says about them
What the code doesBodyjavac says
A statement that skips a constantswitch (s) { case S -> n = 1; case M -> n = 2; }compiles
An expression that skips a constantn = switch (s) { case S -> 1; case M -> 2; };the switch expression does not cover all possible input values
A statement that assigns x in all three cases, then reads itint x; switch (s) { case S -> x = 1; case M -> x = 2; case L -> x = 3; } n = x;variable x might not have been initialized
The same with an expressionint x = switch (s) { case S -> 1; case M -> 2; case L -> 3; }; n = x;compiles
A block that ends without yieldn = switch (s) { case S -> 1; case M -> 2; case L -> { n++; } };switch rule completes without providing a value
return inside a switch expressionn = switch (s) { case S -> 1; case M -> 2; case L -> { return; } };attempt to return out of a switch expression
The same label twicen = switch (s) { case S -> 1; case M, S -> 2; case L -> 3; };duplicate case label
Arrow and colon cases in one switchn = switch (s) { case S -> 1; case M: yield 2; default -> 3; };different case kinds used in the switch

The first four rows show why expressions are safer. A statement may skip a constant, while the same cases as an expression are rejected, because the result would be undefined for L. Even when a statement assigns x in all three cases, javac says it "might not have been initialized". An enum switch statement is not treated as exhaustive, since a new constant could appear at run time. The expression version compiles, which is the strongest practical reason to prefer expressions.

The other rows are about how an expression ends. Every arm must give a value or throw, and return cannot jump out of a switch expression, nor can break or continue to an outer loop. A label cannot appear twice, even when one copy is in a comma list. Last, one switch cannot mix arrow and colon cases.

Which form to use

Switch forms compared
Colon cases case X:Arrow cases case X ->
Falls throughYes, until breakNever
Several labelscase 1: case 2: or case 1, 2:case 1, 2 ->
As a statementNot checked for exhaustiveness (without patterns)Not checked for exhaustiveness (without patterns)
As an expressionEvery path ends with yield, and it must be exhaustiveAn expression, a block with yield, or throw, and it must be exhaustive
  • To compute a value from a selector, use an arrow switch expression.
  • To run different side effects per case, use an arrow switch statement.
  • Over an enum, use an expression without default, so a new constant causes a compile error instead of a silent default.
  • Deliberate fall-through is rarely clearer than a comma list, so keep colon cases for old code.
  • To branch on the type of an object, use pattern matching for switch (Java 21).