Language advanced

Primitive types in patterns

Pattern matching now works with primitive types, not just objects.

✕ Java 8
String classify(int code) {
    if (code >= 200 && code < 300)
        return "success";
    else if (code >= 400 && code < 500)
        return "client error";
    else
        return "other";
}
✓ Java 25 (Preview)
String classify(int code) {
    return switch (code) {
        case int c when c >= 200
            && c < 300 -> "success";
        case int c when c >= 400
            && c < 500 -> "client error";
        default -> "other";
    };
}
📦

No boxing

Match primitives directly — no Integer wrapper needed.

🎯

Pattern consistency

Same pattern syntax for objects and primitives.

Better performance

Avoid autoboxing overhead in pattern matching.

Old Approach
Manual Range Checks
Modern Approach
Primitive Patterns
Since JDK
25
Difficulty
advanced
Primitive types in patterns
Available

Preview in JDK 25 (third preview, JEP 507). Requires --enable-preview.

How it works

Java 25 extends pattern matching to primitive types. You can use int, long, double etc. in switch patterns with when guards, eliminating the need for boxing or manual range checks.

Share 𝕏 🦋 in