What changed in Java 22

Unnamed variables, and the foreign function API goes final

The release that made calling native code a supported, safe operation instead of JNI, and added a small syntax that removes a whole category of unused-variable noise.

Released 2024-03 · 3 features · 5 questions · 0 scenarios

Features

Unnamed variables and patterns

standardJEP 456

An underscore stands in for a variable or pattern component you must declare but will not use.

The problem it solved

Code was littered with names like ignored or unused, which read as meaningful and invited static-analysis warnings for being unread.

How you did it before

Naming the variable something like ignored, or destructuring every record component even when only one mattered.

Needs JDK 22 — this site builds on 21, so this sample is not verified
// Requires JDK 22 — not compiled on this build.
record Point(int x, int y) {}
Object o = new Point(3, 4);
if (o instanceof Point(int x, _)) {
    System.out.println("x only: " + x);
}

Asked as

  • Where can you use an unnamed variable?
  • Why is _ better than naming it ignored?

Foreign Function and Memory API

standardJEP 454

A supported API for calling native code and accessing off-heap memory without writing JNI or using sun.misc.Unsafe.

The problem it solved

JNI required C glue code, was error-prone and slow to develop against, and the alternative — sun.misc.Unsafe — was never a public API and is now being removed.

How you did it before

JNI with hand-written native shims, JNA, or sun.misc.Unsafe for off-heap memory, none of which were both safe and supported.

Journey: Incubator from 14, preview 19-21, final in 22.

Asked as

  • What replaced JNI and sun.misc.Unsafe?
  • Why is off-heap memory access something you might need?

Launch multi-file source-code programs

standardJEP 458

java Main.java now compiles and runs a program spread across several source files, extending the single-file launch from 11.

The problem it solved

Single-file launch stopped being useful the moment a script grew a second class, forcing a build tool for something still script-sized.

How you did it before

A build step, or squeezing everything into one file to keep the single-file launcher working.

Asked as

  • How far can you get without a build tool now?

    Other versions