Language Intermediate

Replace if-else instanceof chains with clean switch type patterns.

โœ• Java 8
String format(Object obj) {
    if (obj instanceof Integer i)
        return "int: " + i;
    else if (obj instanceof Double d)
        return "double: " + d;
    else if (obj instanceof String s)
        return "str: " + s;
    return "unknown";
}
โœ“ Java 21+
String format(Object obj) {
    return switch (obj) {
        case Integer i -> "int: " + i;
        case Double d  -> "double: " + d;
        case String s  -> "str: " + s;
        default        -> "unknown";
    };
}
See a problem with this code? Let us know.
๐Ÿ“

Structured dispatch

Switch makes the branching structure explicit and scannable.

๐ŸŽฏ

Expression form

Returns a value directly โ€” no mutable variable needed.

โœ…

Exhaustiveness

The compiler ensures all types are handled.

Old Approach
if-else Chain
Modern Approach
Type Patterns
Since JDK
21
Difficulty
Intermediate
Pattern matching in switch
Available

Widely available since JDK 21 LTS (Sept 2023)

Pattern matching in switch lets you match on types directly, combining the type test, cast, and binding in one concise case label. The compiler checks completeness.

Share ๐• ๐Ÿฆ‹ in โฌก