Language Zaawansowany

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";
    };
}
Widzisz problem z tym kodem? Daj nam znać.
📦

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.

Stare podejście
Manual Range Checks
Nowoczesne podejście
Primitive Patterns
Od JDK
25
Poziom trudności
Zaawansowany
Primitive types in patterns
Preview

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

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.

Udostępnij 𝕏 🦋 in