Easy java java-21

What are switch expressions?

The 30 second answer

Since Java 14, switch can be an expression that returns a value. The arrow form has no fall-through, so no forgotten break. One case can list several labels, and for a block you return the value with yield. Because it must always produce a value, the compiler checks it is exhaustive, so for an enum you either cover every constant or add a default.

Switch expressions were previewed in Java 12 and 13 and became final in Java 14.

int days = switch (month) {
    case FEB -> 28;
    case APR, JUN, SEP, NOV -> 30;
    default -> 31;
};

String label = switch (code) {
    case 200 -> "ok";
    case 404 -> "missing";
    default -> {
        log.warn("unexpected {}", code);
        yield "error";
    }
};

The arrow form can also be used in switch statements. When a switch expression over an enum covers every constant without a default, the compiler adds an implicit default that throws if an unknown constant appears at runtime (for example after the enum is recompiled with a new value).

Sources: JEP 361: Switch Expressions, JLS 15.28 switch Expressions

Sources (0)
See inline citations in the answer above.