Primitive types in patterns (preview)

Java 23 Course · lesson 4 of 15 · 4 min read

Pattern matching stops being reference-only, and the switch finally covers every type.

Open this lesson in the learning hub

Key points

  • Until 23, instanceof and pattern switch worked on reference types only.
  • JEP 455 extends patterns to int, long, double and the rest.
  • It makes the match safe: a pattern only matches if the value fits without losing information.
  • So case byte b matches 100 but not 300, which a plain cast would silently wrap to 44.
  • This is the piece that makes exhaustive switches over primitives possible.

Example

// Java 23 preview (JEP 455) - requires --enable-preview, will not compile on 21.
//
//   static String classify(int value) {
//       return switch (value) {
//           case byte  b -> "fits in a byte: "  + b;    // only if -128..127
//           case short s -> "fits in a short: " + s;
//           case int   i -> "needs a full int: " + i;
//       };
//   }
//
//   classify(100);    -> "fits in a byte: 100"
//   classify(300);    -> "fits in a short: 300"      byte pattern did NOT match
//   classify(70000);  -> "needs a full int: 70000"
//
// Why this matters, demonstrated on Java 21 with plain casts:
public class Main {
    public static void main(String[] args) {
        int[] values = { 100, 300, 70000 };
        for (int v : values) {
            byte narrowed = (byte) v;                 // silent, lossy
            System.out.println("value " + v + "  ->  (byte) gives " + narrowed +
                (narrowed == v ? "   (safe)" : "   (LOST INFORMATION)"));
        }
        System.out.println("a primitive pattern simply would not match in the lossy cases");
    }
}

A primitive pattern matches only when the value fits - it will not quietly truncate like a cast.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 23 Course course, and every lesson in it is listed on the Java 23 Course contents page.