Primitive Types in Patterns (JEP 507 – Third Preview)

Primitive Types in Patterns (JEP 507 – Third Preview)

A complete guide to primitive type patterns in Java: instanceof as a safe cast, switch on long/float/double/boolean, primitive components in record patterns, exhaustiveness, dominance, and the gotchas.

Java 25 finally lets primitives take full part in pattern matching: instanceof, switch and record patterns now work with int, long, double, boolean and the rest.

In one sentence: JEP 507 lets you use int, long, double, boolean and every other primitive type anywhere a pattern can go. It also turns instanceof into a check for “can this value be converted without losing information?”

1. Where this feature sits

Primitive types in patterns is a preview language feature from Project Amber, the OpenJDK project behind records, sealed types and pattern matching. It has been previewed several times:

JDKJEPStageChanges
23JEP 455First previewInitial design
24JEP 488Second previewNone
25 (LTS)JEP 507Third previewNone. Same design as 455.
26JEP 530Fourth previewStronger unconditional exactness, stricter dominance checks
27JEP 532Fifth previewStill in preview

This guide covers the JEP 507 design as it ships in JDK 25. Section 12 lists the JDK 26 changes so your code keeps compiling when you upgrade.

It is still a preview feature as of JDK 27. Use --enable-preview, and don’t ship it in production code that must compile on future JDKs without changes.


2. The problem: primitives were second-class in pattern matching

Java 16–21 introduced pattern matching for instanceof, record patterns and pattern matching for switch. All of these only worked with reference types. Primitives had five specific limitations:

  1. switch could not use primitive type patterns. You could write case Integer i, but not case int i. The usual “catch everything else” branch was a default that couldn’t name the value or put a guard on it.
  2. Record patterns needed the exact component type. A record with a double component could only be deconstructed as (double d), even when you wanted an int.
  3. instanceof could not use primitive type patterns. There was no x instanceof byte b.
  4. instanceof could not test against a primitive type at all. Even x instanceof int was illegal.
  5. switch only accepted byte, short, char, int (plus their boxes, String and enums). It did not accept long, float, double or boolean.

Here is the kind of code this produced. It’s a manual range check followed by a cast:

// Before: you do the range check, then cast and hope you got it right
static String toByteOld(int value) {
    if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
        byte b = (byte) value;
        return "fits in a byte: " + b;
    }
    return "does not fit: " + value;
}

With JEP 507:

// After: the language does the check
static String toByte(int value) {
    if (value instanceof byte b) {
        return "fits in a byte: " + b;
    }
    return "does not fit: " + value;
}

toByte(100) → fits in a byte: 100, toByte(300) → does not fit: 300.


3. The core idea: exact conversions

Everything in JEP 507 depends on one concept. A conversion is exact if it loses no information. For a reference cast, that also means it doesn’t throw.

There are two kinds:

3.1 Unconditionally exact: safe for every value of the source type

The compiler knows this from the types alone, so no runtime check is needed.

  • Widening integral conversions: byte → short → int → long, char → int
  • byte, short, char → float or double
  • int → double (a double has 53 bits of mantissa, enough for any int)
  • float → double
  • Boxing: int → Integer
  • Widening reference conversions: String → Object

3.2 Conditionally exact: safe for some values only

These need a runtime test.

  • Narrowing: long → int, int → byte, double → int, …
  • Lossy widening: int → float and long → float/double. They are called “widening” but can silently round.
  • Reference downcasts: Object → String is exact only if the object really is a String.

int → float is the surprise. A float has only 24 bits of precision, so 16_777_217 (2²⁴ + 1) can’t be stored exactly. Plain assignment (float f = i;) silently rounds it to 16_777_216.0. With JEP 507, i instanceof float returns false for that value.

3.3 How the runtime test works

  • Integral targets (long → int, double → int, …): convert, convert back, and compare with ==. If you get the same value back, the conversion was exact.
  • Floating-point targets (int → float, double → float): compare by representation equivalence, the same rule Float.equals / Double.equals uses. This has two consequences you might not expect:
    • Double.NaN instanceof float → true (NaN is represented in both types)
    • -0.0 instanceof int → false (int has no negative zero, so the sign is lost)

boolean is a special case: it converts only to itself (and to Boolean).

flowchart TD
    A["value of type S tested against pattern T t"] --> B{"Does a cast S → T exist?"}
    B -- no --> C["Compile-time error"]
    B -- yes --> D{"Is S → T unconditionally exact?"}
    D -- yes --> E["Always matches (if non-null). No runtime check"]
    D -- no --> F{"Runtime: is the conversion exact for this value?"}
    F -- yes --> G["Match: t is bound to the converted value"]
    F -- no --> H["No match"]

4. instanceof as a safe-cast check

JEP 507 removes the rule that both sides of instanceof must be reference types. x instanceof T now means:

Can x be converted to T without losing information?

No new conversions are added to the language. instanceof is allowed only where a cast already exists, and the result shows whether that cast would be exact.

Each result below comes from running the code on JDK 25 with --enable-preview:

ExpressionResultWhy
byte b = 42; b instanceof inttrueUnconditionally exact
int i = 42; i instanceof bytetrue42 fits in −128..127
int i = 1000; i instanceof bytefalseOut of range
int i = 16_777_217; i instanceof floatfalseWould round
int i = 16_777_217; i instanceof doubletrueUnconditionally exact
float f = 1000.0f; f instanceof inttrueWhole number in range
float f = 3.5f; f instanceof intfalseFraction would be lost
double d = 1000.0; d instanceof floattrueRepresentable
long l = Long.MAX_VALUE; l instanceof intfalseOut of range
Integer ii = 16_777_217; ii instanceof floatfalseUnboxed, then would round
Integer ii = 16_777_217; ii instanceof doubletrueUnboxing + exact widening
double d = Double.NaN; d instanceof floattrueNaN ≡ NaN by representation
double d = -0.0; d instanceof intfalseSign of zero is lost
boolean b; b instanceof charcompile errorNo cast exists

This also makes instanceof T and instanceof T t consistent. Before, you could write the binding form with reference types only. Now both forms work with every type.


5. Primitive type patterns in instanceof

A type pattern T t combines two things: a test (“is this exact?”) and a conversion (“give me the converted value as t”). It’s the same as instanceof plus a cast, except the cast can’t go wrong.

long fromDatabase = resultSet.getLong("quantity");

if (fromDatabase instanceof int qty) {
    inventory.reserve(qty);            // qty is guaranteed to equal fromDatabase
} else {
    throw new IllegalStateException("Quantity overflow: " + fromDatabase);
}

Compare this with Math.toIntExact(long), which throws an exception. The pattern version gives you a branch, works for any pair of primitive types, and also works with float/double, where no toIntExact equivalent exists.


6. Primitive type patterns in switch

6.1 Naming the “everything else” case

Before, a switch on int with only constants needed a default that couldn’t see the value. Now the last case can be a pattern with a guard:

static String httpStatus(int code) {
    return switch (code) {
        case 200 -> "OK";
        case 404 -> "Not Found";
        case int c when c >= 100 && c < 200 -> "Informational " + c;
        case int c when c >= 500             -> "Server error " + c;
        case int c                           -> "Other status " + c;
    };
}

case int c on an int selector is unconditional: it matches every value. That’s why the switch expression is exhaustive without a default.

6.2 Choosing the narrowest type that fits

Because each type pattern performs an exactness test, a switch can go from the narrowest type to the widest:

static String narrowest(long v) {
    return switch (v) {
        case byte b  -> "byte "  + b;
        case short s -> "short " + s;
        case int i   -> "int "   + i;
        case long l  -> "long "  + l;
    };
}
// narrowest(5)              → byte 5
// narrowest(30_000)         → short 30000
// narrowest(100_000)        → int 100000
// narrowest(3_000_000_000L) → long 3000000000

This works for serialisation formats (CBOR, MessagePack, Protobuf varints) that choose the smallest encoding for a value.

6.3 Mixing reference and primitive tests

You can also use primitive instanceof inside guards:

static String fromObject(Object o) {
    return switch (o) {
        case Integer i when i.intValue() instanceof byte b      -> "small int " + b;
        case Integer i                                          -> "int " + i;
        case Double d  when d.doubleValue() instanceof int n    -> "whole double " + n;
        case Double d                                           -> "double " + d;
        default                                                 -> "other";
    };
}

Why i.intValue() and not just i instanceof byte? See Gotcha #1 in section 11.


7. switch on long, float, double and boolean

switch now accepts all primitive types and their boxes as selectors.

7.1 long

static String classify(long amountInCents) {
    return switch (amountInCents) {
        case 0L                                   -> "zero";
        case long a when a < 0                    -> "refund";
        case long a when a > 1_000_000_00L        -> "high-value";
        case long a                               -> "regular";
    };
}

7.2 double and float

static String ratio(double r) {
    return switch (r) {
        case 0.0                          -> "none";
        case 1.0                          -> "full";
        case double x when Double.isNaN(x) -> "not a number";
        case double x when x > 0 && x < 1  -> "partial";
        case double x                      -> "out of range: " + x;
    };
}

Rules for floating-point constants:

  • Constants must have the selector’s type. With a float selector, write case 0f, not case 0:
    error: constant label of type int is not compatible with switch selector type float
    
  • Duplicate labels are detected by representation equivalence. case 1.0f and case 0.999999999f are duplicates, because the second literal rounds to 1.0f:
    error: duplicate case label
    

7.3 boolean

static String yesNo(boolean flag) {
    return switch (flag) {
        case true  -> "yes";
        case false -> "no";
    };
}

Listing both true and false makes the switch exhaustive. Adding a default is an error:

error: switch has both boolean values and a default label

A boolean switch is more useful as an expression with guards than as a replacement for the ternary operator, for example case true when retries > 3 -> ….


8. Primitive types in record patterns

This is the example the JEP itself uses to motivate the feature. Take a small JSON model:

sealed interface JsonValue permits JsonString, JsonNumber, JsonBool {}
record JsonString(String s)  implements JsonValue {}
record JsonNumber(double d)  implements JsonValue {}   // JSON numbers are doubles
record JsonBool(boolean b)   implements JsonValue {}

Before JEP 507 you could only write JsonNumber(double d) and then cast it yourself, which could lose information. Now a nested int pattern matches only when the double holds an exact integer:

if (json instanceof JsonNumber(int age)) {
    // age is a real int: 30.0 matches, 30.7 does not
}

The same works in a switch:

static String describe(JsonValue json) {
    return switch (json) {
        case JsonNumber(int n)    -> "integer " + n;
        case JsonNumber(double d) -> "decimal " + d;
        case JsonString(String s) -> "string " + s;
        case JsonBool(boolean b)  -> "bool " + b;
    };
}
// describe(new JsonNumber(42))   → integer 42
// describe(new JsonNumber(42.5)) → decimal 42.5

JsonNumber(double d) is unconditional for the component, so together with the other cases the sealed hierarchy is fully covered and no default is needed.


9. Exhaustiveness

A switch expression, and any switch statement that uses patterns, must be exhaustive: every possible input must be handled.

  • A pattern that is unconditional on the selector type (case int i on an int, case long l on an int) makes the switch exhaustive by itself.
  • A conditionally exact pattern does not. case byte b on an int selector leaves values uncovered:
    error: the switch expression does not cover all possible input values
    
  • Boxed selectors: if the selector is a wrapper type W (such as Byte) for primitive P, a pattern T t covers W when P → T is unconditionally exact. So this compiles:

    static int boxed(Byte b) {
        return switch (b) {
            case int p -> p;   // byte → int is unconditionally exact
        };
    }
    

    null is still left over. Passing null throws NullPointerException unless you add case null.


10. Dominance

A pattern dominates another if it matches every value the other matches. An unguarded pattern can’t come before a pattern it dominates, because the later case would never run.

For type patterns: T t dominates U u if T t is unconditional on U. Examples:

  • long l dominates int i (every int converts exactly to long)
  • double d dominates int i
  • int i does not dominate float f, and float f does not dominate int i (neither direction is unconditionally exact)

On JDK 25, putting a broader pattern first on an int selector is rejected:

switch (x) {            // x is int
    case long q -> {}   // unconditional on int
    case int i  -> {}   // error on JDK 25: duplicate unconditional pattern
}

The rule of thumb is the same as for reference types: put the narrow cases first and the broad ones last.


11. Gotchas and edge cases

Gotcha #1: a wrapper does not narrow to a different primitive. Integer i; i instanceof byte is a compile error (“Integer cannot be converted to byte”), and so is Double d; d instanceof int. A cast from a wrapper to a primitive allows unboxing followed by widening only, never narrowing. JEP 507 adds no new conversions, so the check isn’t available either. Unbox explicitly first: i.intValue() instanceof byte b. (Integer → int, Integer → long and Integer → double are fine.)

Gotcha #2: “widening” is not always safe. int → float, long → float and long → double are widening conversions in the JLS, but they are not unconditionally exact. Don’t assume case float f catches every int.

Gotcha #3: NaN and −0.0. NaN matches a float pattern (representation equivalence). -0.0 does not match an int pattern. If NaN is valid in your domain, check for it in a guard first.

Gotcha #4: constant types. case 0 on a float selector is an error. Write 0f. On a long selector, 0L is clearest.

Gotcha #5: boolean + default. true + false + default is an error, not a harmless extra branch.

Gotcha #6: it’s a preview feature. The JDK 26 fourth preview already changed the rules (section 12). Code that compiles on JDK 25 may not compile on later JDKs.


12. What changed after JEP 507 (JDK 26, JEP 530)

JEP 507 itself made no changes compared with JEP 455 and JEP 488. The next preview, JEP 530 in JDK 26, made two changes. Both can turn previously valid code into compile errors:

  1. Better definition of unconditional exactness. Constant expressions are also checked: if a constant’s narrowing or lossy-widening conversion loses nothing (for example 42 → byte, or 4096 → float), the compiler treats it as exact.
  2. Stricter dominance checks in switch:
    • A constant label is rejected if an earlier pattern already matches it:

      byte x = ...;
      switch (x) {
          case short s -> {}
          case 42      -> {}   // compiles on JDK 25, error on JDK 26+
      }
      
    • An unconditional pattern must be the last label. Anything after it is dominated:

      int x = ...;
      switch (x) {
          case int _   -> {}
          case float _ -> {}   // compiles on JDK 25, error on JDK 26+
      }
      
    • This also applies to reference types. If the selector has type A, case A _ is unconditional, so a following case B _ (where B is an unrelated interface) is now an error.

I confirmed that both snippets above compile on JDK 25, so these really are behaviour changes between versions. JDK 27 continues with a fifth preview (JEP 532).

Put unconditional patterns last and constants before any pattern that covers them. Code written that way compiles under every preview so far.


13. Trying it out

Single-file program

java --enable-preview --source 25 Demo.java

This runs Demo.java directly, without a separate compile step.

javac

javac --enable-preview --release 25 Demo.java
java  --enable-preview Demo

Without the flag you get:

error: primitive patterns are a preview feature and are disabled by default.
  (use --enable-preview to enable primitive patterns)

Maven

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <release>25</release>
    <compilerArgs>
      <arg>--enable-preview</arg>
    </compilerArgs>
  </configuration>
</plugin>

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>--enable-preview</argLine>
  </configuration>
</plugin>

Classes compiled with --enable-preview are tied to that exact JDK version. A class built on JDK 25 with preview features won’t run on JDK 26 without recompiling.

IntelliJ IDEA

Open ⌘ + ; (Ctrl + Alt + Shift + S on Windows/Linux) and set the language level to 25 (Preview) in Project Structure → Project.


14. Cheatsheet

You want to…Write
Check whether a value fits a narrower typeif (l instanceof int i) { … }
Narrow without silent truncationvalue instanceof byte b instead of (byte) value
Check exactness without bindingd instanceof float
Name and guard the “rest” of an int switchcase int c when c > 500 -> …
Switch on long / double / float / booleanJust do it. Constants must match the selector type
Pick the smallest fitting typecase byte b → case short s → case int i → case long l
Pull an int out of a double record componentcase JsonNumber(int n) -> …
Cover a Byte selector exhaustivelycase int p -> … (+ case null if needed)
Avoid JDK 26+ breakageUnconditional pattern last; constants before patterns that cover them

Key terms

  • Exact conversion: no information lost.
  • Unconditionally exact: exact for every value of the source type, checked at compile time.
  • Conditionally exact: needs a runtime check.
  • Unconditional pattern: matches every non-null value of the selector type.
  • Dominance: an earlier pattern that matches everything a later one does makes the later one unreachable.

References