Switch expressions

suggest change

Java 14 added a second form of switch (JEP 361). It uses case X -> labels instead of case X:, never falls through, can list several values in one label, and can be used as an expression that produces a value. Java 21 extended it with pattern matching and made exhaustiveness checks stricter.

This article covers:

The examples are single files you run with java Example.java. Output is from JDK 25.

The classic case X: form is covered in Switch statement. Type patterns, record patterns, guards and sealed hierarchies in switch are in Pattern matching.

Arrow labels

A case X -> label is followed by a single expression, a block in braces, or a throw statement. Only that one arm runs. There's no break, and no way to fall into the next case by accident:

public class ArrowLabels {
    static void describe(int n) {
        switch (n) {
            case 0 -> System.out.println(n + ": zero");
            case 1, 2, 3 -> System.out.println(n + ": small");
            case 4, 5, 6 -> {
                String size = "medium";
                System.out.println(n + ": " + size);
            }
            default -> System.out.println(n + ": large");
        }
    }

    public static void main(String[] args) {
        for (int n : new int[] {0, 2, 5, 42}) {
            describe(n);
        }
    }
}
0: zero
2: small
5: medium
42: large

Arrow labels can be used in a plain switch statement like the one above. You can switch any old-style statement to arrows and drop the breaks, as long as it doesn't rely on fall-through.

switch as an expression

The bigger change is that switch can produce a value. Here's the same calculation written both ways:

import java.time.Month;

public class DaysInMonth {
    static int daysOld(Month month, boolean leapYear) {
        int days;
        switch (month) {
            case FEBRUARY:
                days = leapYear ? 29 : 28;
                break;
            case APRIL:
            case JUNE:
            case SEPTEMBER:
            case NOVEMBER:
                days = 30;
                break;
            default:
                days = 31;
        }
        return days;
    }

    static int daysNew(Month month, boolean leapYear) {
        return switch (month) {
            case FEBRUARY -> leapYear ? 29 : 28;
            case APRIL, JUNE, SEPTEMBER, NOVEMBER -> 30;
            default -> 31;
        };
    }

    public static void main(String[] args) {
        for (Month m : new Month[] {Month.JANUARY, Month.FEBRUARY, Month.APRIL}) {
            System.out.println(m + " " + daysOld(m, false) + " " + daysNew(m, false)
                    + " (leap: " + daysNew(m, true) + ")");
        }
        String label = "Q" + switch (Month.MAY) {
            case JANUARY, FEBRUARY, MARCH -> 1;
            case APRIL, MAY, JUNE -> 2;
            case JULY, AUGUST, SEPTEMBER -> 3;
            case OCTOBER, NOVEMBER, DECEMBER -> 4;
        };
        System.out.println(label);
    }
}
JANUARY 31 31 (leap: 31)
FEBRUARY 28 28 (leap: 29)
APRIL 30 30 (leap: 30)
Q2

daysOld declares a variable, assigns it in every branch and has to remember break each time. Leave out one break and APRIL returns 31. If you forget the assignment in one branch, the compiler complains that days might not have been initialized, but only because days has no initial value.

daysNew returns the switch directly. A switch expression can go anywhere an expression can: on the right side of =, after return, as a method argument, or in string concatenation as in the "Q" + switch (...) example. It ends with ; when it's part of a statement, because the whole switch { ... } is just an expression.

The quarter example has no default. All twelve Month constants are listed, so the compiler knows the switch covers every value. More on that in the exhaustiveness section below.

yield: a value from a block

When an arm needs more than one expression, use a block and return its value with yield:

public class Yield {
    static int parsePort(String s) {
        int port = switch (s) {
            case "http" -> 80;
            case "https" -> 443;
            default -> {
                int p;
                try {
                    p = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("bad port: " + s);
                }
                if (p < 1 || p > 65535) {
                    throw new IllegalArgumentException("port out of range: " + p);
                }
                yield p;
            }
        };
        return port;
    }

    public static void main(String[] args) {
        for (String s : new String[] {"http", "https", "8443", "99999", "ftp"}) {
            try {
                System.out.println(s + " -> " + parsePort(s));
            } catch (IllegalArgumentException e) {
                System.out.println(s + " -> " + e.getMessage());
            }
        }
    }
}
http -> 80
https -> 443
8443 -> 8443
99999 -> port out of range: 99999
ftp -> bad port: ftp

Every block arm in a switch expression must end with yield or throw. If it can finish without either, compilation fails:

return switch (n) {
    case 1 -> 10;
    default -> {
        System.out.println("other");
    }
};
NoYield.java:7: error: switch rule completes without providing a value
            }
            ^
  (switch rules in switch expressions must either provide a value or throw)

An arm that only throws doesn't need a block. default -> throw new IllegalArgumentException(...) is a common way to reject unexpected values.

yield is a contextual keyword, not a reserved word, so existing variables or methods called yield still compile. A bare call to a method named yield is now an error, though:

YieldName.java:4: error: yield outside of switch expression
        yield(5);
        ^
  (to invoke a method called yield, qualify the yield with a receiver or type name)

Write this.yield(5) or YieldName.yield(5) instead. (Thread.yield() is always called that way, so it isn't affected.)

Colon labels in a switch expression

A switch expression can also use the old case X: labels. Then you give the value with yield, and fall-through works the way it does in a statement:

public class ColonYield {
    static String kind(char c) {
        return switch (c) {
            case 'a', 'e', 'i', 'o', 'u':
                yield "vowel";
            case ' ':
            case '\t':
                yield "space";
            default:
                if (Character.isDigit(c)) {
                    yield "digit";
                }
                yield "other";
        };
    }

    public static void main(String[] args) {
        for (char c : "a 7x".toCharArray()) {
            System.out.println("'" + c + "' " + kind(c));
        }
    }
}
'a' vowel
' ' space
'7' digit
'x' other

This form is legal but rarely useful. Arrow labels are shorter and safer. You can't mix the two kinds of label in one switch:

Mixed.java:5: error: different case kinds used in the switch
            case 2: yield 20;
            ^

Exhaustiveness

A switch expression must produce a value for every possible input. For int or String that means you need a default. For an enum, listing every constant is enough:

public class Exhaustive {
    enum Light { RED, YELLOW, GREEN }

    static String action(Light light) {
        return switch (light) {
            case RED -> "stop";
            case YELLOW -> "slow down";
            case GREEN -> "go";
        };
    }

    static void statement(Light light) {
        // an arrow switch *statement* over an enum doesn't have to be exhaustive
        switch (light) {
            case RED -> System.out.println("statement: stop");
            case GREEN -> System.out.println("statement: go");
        }
    }

    public static void main(String[] args) {
        for (Light l : Light.values()) {
            System.out.println(l + ": " + action(l));
            statement(l);
        }
    }
}
RED: stop
statement: stop
YELLOW: slow down
GREEN: go
statement: go

Leave out a constant and you get a compile error, not a runtime surprise:

enum Size { SMALL, MEDIUM, LARGE }

static String label(Size s) {
    return switch (s) {
        case SMALL -> "S";
        case MEDIUM -> "M";
    };
}
Missing.java:5: error: the switch expression does not cover all possible input values
        return switch (s) {
               ^

This is the main reason to leave out default when switching over an enum. When someone adds XLARGE to Size, every switch expression that doesn't handle it stops compiling. A default arm would silently swallow the new constant.

The statement method shows that the rule doesn't apply to an ordinary switch statement over an enum, String or int. YELLOW matches nothing, so nothing runs. The rule does apply to statements that use the Java 21 features: a switch statement with a pattern label or case null must be exhaustive too.

static void f(String s) {
    switch (s) {
        case null -> System.out.println("null");
        case "a" -> System.out.println("a");
    }
}
NullStmt.java:3: error: the switch statement does not cover all possible input values
        switch (s) {
        ^

When the enum changes without a recompile

Exhaustiveness is checked at compile time. What if the enum gets a new constant and the class with the switch isn't recompiled? The compiler adds a hidden default arm that throws. To see it, compile Shop against a 3-constant Size, then recompile only Size with a fourth constant XLARGE:

public class Shop {
    static String label(Size s) {
        return switch (s) {
            case SMALL -> "S";
            case MEDIUM -> "M";
            case LARGE -> "L";
        };
    }

    public static void main(String[] args) {
        for (Size s : Size.values()) {
            System.out.println(s + " -> " + label(s));
        }
    }
}
$ javac -d out v1/Size.java Shop.java && java -cp out Shop
SMALL -> S
MEDIUM -> M
LARGE -> L
$ javac -d out v2/Size.java && java -cp out Shop
SMALL -> S
MEDIUM -> M
LARGE -> L
Exception in thread "main" java.lang.MatchException
	at Shop.label(Shop.java:3)
	at Shop.main(Shop.java:12)

With --release 21 or newer the hidden arm throws MatchException. Classes compiled for Java 14-20 throw IncompatibleClassChangeError instead. Either way the error is loud, never a silent wrong value.

Sealed interfaces and qualified enum constants

Exhaustiveness also works with sealed types: a switch that handles every permitted subtype needs no default. Pattern matching covers this with records. Since Java 21 a case label can also name an enum constant with its type, which lets one switch cover the constants of several enums that implement the same sealed interface:

public class Qualified {
    sealed interface Currency permits Coin, Note {}
    enum Coin implements Currency { PENNY, NICKEL, DIME }
    enum Note implements Currency { ONE, FIVE }

    static int cents(Currency c) {
        return switch (c) {
            case Coin.PENNY -> 1;
            case Coin.NICKEL -> 5;
            case Coin.DIME -> 10;
            case Note.ONE -> 100;
            case Note.FIVE -> 500;
        };
    }

    public static void main(String[] args) {
        System.out.println(cents(Coin.DIME) + cents(Note.FIVE));
    }
}
510

The type of a switch expression

If all arms are numbers, the result uses the usual numeric promotion, just like the ?: operator. If the arms have unrelated types, the result is their common supertype:

public class Types {
    enum Unit { BYTES, KB, MB }

    public static void main(String[] args) {
        Unit unit = Unit.KB;

        var factor = switch (unit) {
            case BYTES -> 1;
            case KB -> 1024;
            case MB -> 1024.0 * 1024;
        };
        System.out.println(factor + " " + ((Object) factor).getClass().getSimpleName());

        Object mixed = switch (unit) {
            case BYTES -> 1;
            case KB -> "kilo";
            case MB -> 2.5;
        };
        System.out.println(mixed + " " + mixed.getClass().getSimpleName());

        long size = switch (unit) {
            case BYTES -> 1L;
            case KB -> 1024;
            case MB -> 1024 * 1024;
        };
        System.out.println(size);
    }
}
1024.0 Double
kilo String
1024

null and selector types

A switch over a reference type throws NullPointerException when the selector is null, even if there's a default. Since Java 21 you can handle null explicitly with case null, either on its own or combined with default:

public class Nulls {
    static String old(String cmd) {
        return switch (cmd) {
            case "start" -> "starting";
            case "stop" -> "stopping";
            default -> "unknown";
        };
    }

    static String withNull(String cmd) {
        return switch (cmd) {
            case "start" -> "starting";
            case "stop" -> "stopping";
            case null, default -> "unknown";
        };
    }

    public static void main(String[] args) {
        System.out.println(withNull(null));
        try {
            System.out.println(old(null));
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }
    }
}
unknown
NullPointerException

Without patterns, the selector can be char, byte, short, int, their wrapper types, String or an enum. Any other reference type works with type patterns (see Pattern matching). long, float, double and boolean are not allowed in JDK 25:

LongSel.java:3: error: primitive patterns are a preview feature and are disabled by default.
        return switch (n) {
                      ^
  (use --enable-preview to enable primitive patterns)

The error message points to "primitive types in patterns" (JEP 507), which is a preview feature in JDK 25. With --enable-preview, switch (n) on a long with case 3_000_000_000L -> labels compiles and runs. Don't use it in production code until it's final.

Two arms can't match the same value:

Dup.java:5: error: duplicate case label
            case 2, 3 -> "b";
            ^

Strings and case-insensitive matching

A switch on strings compares with equals, so it's case-sensitive. As explained in Case insensitive switch, normalize the selector first. Several labels per case and a throwing default make a compact parser:

import java.util.Locale;

public class CaseInsensitive {
    static boolean parseBool(String s) {
        return switch (s.strip().toLowerCase(Locale.ROOT)) {
            case "true", "yes", "on", "1" -> true;
            case "false", "no", "off", "0" -> false;
            default -> throw new IllegalArgumentException("not a boolean: " + s);
        };
    }

    public static void main(String[] args) {
        System.out.println(parseBool(" YES ") + " " + parseBool("Off"));
        try {
            parseBool("maybe");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
true false
not a boolean: maybe

Use toLowerCase(Locale.ROOT), not plain toLowerCase(). With a Turkish default locale, "I".toLowerCase() is the dotless ı, so input like "ID" would never match a label "id".

return, break and continue

A switch expression must produce a value or throw. You can't jump out of it:

int x = switch (n) {
    case 1 -> 10;
    default -> { return -1; }
};
Ret.java:5: error: attempt to return out of a switch expression
            default -> { return -1; }
                         ^

break and continue that would leave the expression are rejected the same way ("attempt to continue out of a switch expression").

A switch statement with arrow labels has no such limits. return leaves the method, continue goes to the next iteration of an enclosing loop, and break leaves the switch:

public class Loop {
    public static void main(String[] args) {
        String[] lines = {"# comment", "", "name=app", "END", "ignored=1"};
        for (String line : lines) {
            switch (line.isEmpty() ? ' ' : line.charAt(0)) {
                case '#', ' ' -> {
                    continue;          // next loop iteration
                }
                case 'E' -> {
                    if (line.equals("END")) {
                        System.out.println("done");
                        return;
                    }
                }
                default -> { }
            }
            System.out.println("setting: " + line);
        }
    }
}
setting: name=app
done

When an arm needs to leave the method or the loop, use a statement, not an expression.

When to keep the old form

Arrow labels should be your default. The old case X: form is still the right tool when fall-through is the point, for example when each case adds to what the cases below it do:

import java.util.ArrayList;
import java.util.List;

public class FallThrough {
    enum Role { ADMIN, EDITOR, VIEWER }

    static List<String> permissions(Role role) {
        List<String> perms = new ArrayList<>();
        switch (role) {
            case ADMIN:
                perms.add("delete");
                // fall through
            case EDITOR:
                perms.add("write");
                // fall through
            case VIEWER:
                perms.add("read");
        }
        return perms;
    }

    public static void main(String[] args) {
        for (Role r : Role.values()) {
            System.out.println(r + " " + permissions(r));
        }
    }
}
ADMIN [delete, write, read]
EDITOR [write, read]
VIEWER [read]

With arrows you would repeat perms.add("read") in all three arms. If you do use fall-through, mark it with a // fall through comment so readers know it's deliberate. javac -Xlint:fallthrough warns about every fall-through regardless of comments; put @SuppressWarnings("fallthrough") on the method to silence it. See Pitfall - Missing a break in a switch case.

Some other guidelines:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents