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.
- 1. Where this feature sits
- 2. The problem: primitives were second-class in pattern matching
- 3. The core idea: exact conversions
- 4.
instanceofas a safe-cast check - 5. Primitive type patterns in
instanceof - 6. Primitive type patterns in
switch - 7.
switchonlong,float,doubleandboolean - 8. Primitive types in record patterns
- 9. Exhaustiveness
- 10. Dominance
- 11. Gotchas and edge cases
- 12. What changed after JEP 507 (JDK 26, JEP 530)
- 13. Trying it out
- 14. Cheatsheet
- References
In one sentence: JEP 507 lets you use
int,long,double,booleanand every other primitive type anywhere a pattern can go. It also turnsinstanceofinto 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:
| JDK | JEP | Stage | Changes |
|---|---|---|---|
| 23 | JEP 455 | First preview | Initial design |
| 24 | JEP 488 | Second preview | None |
| 25 (LTS) | JEP 507 | Third preview | None. Same design as 455. |
| 26 | JEP 530 | Fourth preview | Stronger unconditional exactness, stricter dominance checks |
| 27 | JEP 532 | Fifth preview | Still 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:
switchcould not use primitive type patterns. You could writecase Integer i, but notcase int i. The usual “catch everything else” branch was adefaultthat couldn’t name the value or put a guard on it.- Record patterns needed the exact component type. A record with a
doublecomponent could only be deconstructed as(double d), even when you wanted anint. instanceofcould not use primitive type patterns. There was nox instanceof byte b.instanceofcould not test against a primitive type at all. Evenx instanceof intwas illegal.switchonly acceptedbyte,short,char,int(plus their boxes,Stringand enums). It did not acceptlong,float,doubleorboolean.
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→floatordoubleint → double(adoublehas 53 bits of mantissa, enough for anyint)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 → floatandlong → float/double. They are called “widening” but can silently round. - Reference downcasts:
Object → Stringis exact only if the object really is aString.
int → floatis the surprise. Afloathas only 24 bits of precision, so16_777_217(2²⁴ + 1) can’t be stored exactly. Plain assignment (float f = i;) silently rounds it to16_777_216.0. With JEP 507,i instanceof floatreturns 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 ruleFloat.equals/Double.equalsuses. This has two consequences you might not expect:Double.NaN instanceof float→ true (NaN is represented in both types)-0.0 instanceof int→ false (inthas 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
xbe converted toTwithout 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:
| Expression | Result | Why |
|---|---|---|
byte b = 42; b instanceof int | true | Unconditionally exact |
int i = 42; i instanceof byte | true | 42 fits in −128..127 |
int i = 1000; i instanceof byte | false | Out of range |
int i = 16_777_217; i instanceof float | false | Would round |
int i = 16_777_217; i instanceof double | true | Unconditionally exact |
float f = 1000.0f; f instanceof int | true | Whole number in range |
float f = 3.5f; f instanceof int | false | Fraction would be lost |
double d = 1000.0; d instanceof float | true | Representable |
long l = Long.MAX_VALUE; l instanceof int | false | Out of range |
Integer ii = 16_777_217; ii instanceof float | false | Unboxed, then would round |
Integer ii = 16_777_217; ii instanceof double | true | Unboxing + exact widening |
double d = Double.NaN; d instanceof float | true | NaN ≡ NaN by representation |
double d = -0.0; d instanceof int | false | Sign of zero is lost |
boolean b; b instanceof char | compile error | No 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 justi 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
floatselector, writecase 0f, notcase 0:error: constant label of type int is not compatible with switch selector type float - Duplicate labels are detected by representation equivalence.
case 1.0fandcase 0.999999999fare duplicates, because the second literal rounds to1.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 ion anint,case long lon anint) makes the switch exhaustive by itself. - A conditionally exact pattern does not.
case byte bon anintselector 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 asByte) for primitiveP, a patternT tcoversWwhenP → Tis unconditionally exact. So this compiles:static int boxed(Byte b) { return switch (b) { case int p -> p; // byte → int is unconditionally exact }; }nullis still left over. PassingnullthrowsNullPointerExceptionunless you addcase 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 ldominatesint i(everyintconverts exactly tolong)double ddominatesint iint idoes not dominatefloat f, andfloat fdoes not dominateint 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:
- 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, or4096 → float), the compiler treats it as exact. - 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 followingcase B _(whereBis 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-previeware 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 type | if (l instanceof int i) { … } |
| Narrow without silent truncation | value instanceof byte b instead of (byte) value |
| Check exactness without binding | d instanceof float |
| Name and guard the “rest” of an int switch | case int c when c > 500 -> … |
Switch on long / double / float / boolean | Just do it. Constants must match the selector type |
| Pick the smallest fitting type | case byte b → case short s → case int i → case long l |
Pull an int out of a double record component | case JsonNumber(int n) -> … |
Cover a Byte selector exhaustively | case int p -> … (+ case null if needed) |
| Avoid JDK 26+ breakage | Unconditional 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
- JEP 507: Primitive Types in Patterns, instanceof, and switch (Third Preview)
- JEP 455: First Preview · JEP 488: Second Preview
- JEP 530: Fourth Preview (JDK 26)
- JEP 532: Fifth Preview (JDK 27)
- Oracle Java Language Guide: Primitive Types in Patterns, instanceof, and switch
- JLS §5.5 (Casting Contexts), §14.11 (switch), §14.30 (Patterns), §15.20.2 (instanceof)