Java

Switch Expressions (Java 14+)

admin by @admin ADMIN
13m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`switch` is now also an expression — it returns a value. Use `->` arrows for fall-through-free arms; `yield` inside `{ }` blocks for multi-statement arms. No more accidental forgotten `break`.
Java
Raw
enum Status { PENDING, ACTIVE, ARCHIVED, DELETED }

// As an expression — assignable, returnable
String label(Status s) {
    return switch (s) {
        case PENDING                -> "Not yet started";
        case ACTIVE                 -> "In flight";
        case ARCHIVED, DELETED      -> "Gone";          // multi-label arm
    };
}

// Multi-statement arm uses braces + yield
int weight(Status s) {
    return switch (s) {
        case PENDING -> 1;
        case ACTIVE  -> 10;
        case ARCHIVED, DELETED -> {
            log("counting an archived");
            yield 0;
        }
    };
}

// Switch on type (Java 21+)
String describe(Object o) {
    return switch (o) {
        case Integer i when i > 0 -> "positive int " + i;
        case Integer i            -> "non-positive int " + i;
        case String s             -> "string of length " + s.length();
        case null                 -> "null";
        default                   -> "other";
    };
}

void log(String s) { System.out.println(s); }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.