Java 22 to 25: What's New After the OCP 21 Exam (1Z0-831)
Every developer-facing change from Java 22 to 25 that matters for the Java 25 exam (1Z0-831): unnamed variables, flexible constructor bodies, module imports, compact source files, stream gatherers and scoped values, plus what Java 26 and 27 changed and what's still in preview.
kvi5hnuCode Sprout team member12 min readOn this page
Everything in articles 1 to 91 follows Java 21, the version that the 1Z0-830 exam tests. Java has kept moving: a new release every March and September, with a long-term support (LTS) release every two years. Java 25 (September 2025) is the current LTS, and its exam, 1Z0-831, adds the features that became final between Java 22 and 25.
This article collects all of those changes in one place. For each feature you get the rules an exam question could test, and every snippet was compiled on JDK 25. It also covers Java 26 (March 2026) and Java 27 (September 2026), which aren't LTS releases and aren't exam targets, so you know what's settled and what's still moving.

Java 22: unnamed variables and patterns (final)
Since Java 9, _ couldn't be used as an identifier. From Java 22 it means "a variable I must declare but will never use". It can be used:
- as a local variable, a
for-loop or enhanced-forvariable, or a try-with-resources resource:for (var _ : list) count++; - as a
catchparameter:catch (NumberFormatException _) { ... } - as a lambda parameter:
map.forEach((name, _) -> System.out.println(name)); - inside record patterns, for a component you don't need:
case Line(var x1, _, var x2, _) -> - as a whole type pattern:
case Circle _ ->
Rules to know:
- You can declare
_several times in the same scope (var _ = a(); var _ = b();), because none of them is a real name. - You can never read it:
System.out.println(_)doesn't compile. - It isn't allowed for fields or method parameters.
int _ = 3;as a field doesn't compile. - A
caselabel can now list several patterns if none of them declares a binding variable:case Circle _, Square _ -> "round or square";
Java 25: flexible constructor bodies (final)
In Java 21, super(...) or this(...) had to be the first statement of a constructor. Since Java 25, statements may come before it. That part of the constructor is called the prologue:
SavingsAccount(String id, double rate) {
if (rate < 0 || rate > 0.2) throw new IllegalArgumentException("bad rate"); // validate first
this.rate = rate; // assigning this class's own field: allowed
super(id.strip().toUpperCase(Locale.ROOT));
}
The prologue runs before the object is fully set up, so it has strict limits:
- It can validate arguments, compute values for the
super(...)call and assign this class's own fields that have no initializer (without reading them). Assigning a field declared with an initializer, such asint rate = 5;, is a compile error. - It can't read fields or use
thisin any other way, call instance methods such ashelper(), or usesuper.x. Each of these is a compile error: "cannot reference ... before supertype constructor has been called". - It can't contain a
returnstatement.
The field-assignment rule closes an old trap. A superclass constructor that calls an overridden method used to see the subclass's fields at their default values. If you assign them in the prologue, they're already set when the superclass constructor runs.
Java 25: module import declarations (final)
import module java.base; // every public type of every package java.base exports
import module M; imports all public top-level types from every package that module M exports, plus the packages of modules that M requires transitively. It's like writing import p.*; for each of those packages. It works in any source file, modular or not.
When two imports provide the same simple name, the use is ambiguous. For example, import module java.base; plus import module java.desktop; makes List ambiguous (java.util.List or java.awt.List), and using List is a compile error. Fix it with a single-type import (import java.util.List;) or a package wildcard (import java.util.*;). Both kinds of import shadow module imports.
Java 25: compact source files and instance main methods (final)
A small program no longer needs a class declaration or public static void main(String[] args):
// Hello.java, run with: java Hello.java
void main() {
IO.println("Hi " + List.of(1, 2).size()); // prints: Hi 2
}
- A file whose top-level members are methods and fields is a compact source file. The compiler wraps them in an implicitly declared,
finalclass named after the file. Other code can't refer to that class by name. - A compact source file automatically gets
import module java.base;, which is whyListworks above without an import. java.lang.IO(new in Java 25, so no import is needed) offersprintln,printandreadln.- Any class, compact or not, may now have a launchable
mainthat is non-public, non-staticor has no parameters. If a class has both, the version withString[]wins. For an instancemain, the launcher creates an object, so the class needs a non-private no-argument constructor. Otherwise launching fails with "can't find no argument constructor".
Java 24: stream gatherers (final)
Stream.gather(Gatherer) is a new intermediate operation. It's the intermediate-operation counterpart of collect(Collector): you can write custom transformations that keep state, emit any number of results per element or stop early. java.util.stream.Gatherers provides five built-in ones:
| Gatherer | Example with 3, 8, 5, 1, 9, 4, 7 |
|---|---|
windowFixed(3) | [[3, 8, 5], [1, 9, 4], [7]] |
windowSliding(3) | [[3, 8, 5], [8, 5, 1], [5, 1, 9], [1, 9, 4], [9, 4, 7]] |
scan(() -> 0, Integer::sum) | [3, 11, 16, 17, 26, 30, 37] (running results) |
fold(() -> "", (a, n) -> a + n) | one element: "3851947" |
mapConcurrent(4, fn) | map on up to 4 virtual threads at once, keeping the encounter order |
You write your own with Gatherer.of(...) or Gatherer.ofSequential(initializer, integrator, finisher). The integrator receives (state, element, downstream) and returns false to stop the stream early.
Java 25: scoped values (final)
A ScopedValue passes data to the code a method calls without adding parameters to every method. It's a safer replacement for many uses of ThreadLocal:
static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "mira").run(() -> handle()); // USER.get() is "mira" inside
String r = ScopedValue.where(USER, "mira").call(() -> process());
USER.isBound(); // false outside the run/call
USER.orElse("anonymous");
- The binding is immutable and lasts only for the
runorcall. When that call returns, the value is unbound again. Unlike aThreadLocal, there's noset()and nothing to forget toremove(). get()on an unbound value throwsNoSuchElementException.calltakes aScopedValue.CallableOp, which can throw a checked exception of a type the compiler infers.- With structured concurrency (still a preview, see below), child tasks inherit the binding. Bindings are cheap even with millions of virtual threads.
Other final changes from Java 22 to 25
| Release | Change | Why it matters |
|---|---|---|
| 22 | Foreign Function & Memory API (java.lang.foreign) | Off-heap memory and native calls without JNI: Arena, MemorySegment, Linker. A confined arena frees its memory when it's closed. |
| 22 | Launch multi-file source programs | java Main.java also compiles the other .java files it needs from the same directory tree. |
| 23 | Markdown documentation comments | /// comments use Markdown instead of HTML in javadoc. |
| 23 | Generational mode is the ZGC default, and string templates are withdrawn | Don't learn STR."...": it isn't in any final release. |
| 23 | Annotation processing is no longer on by default | Processors on the class path need -proc:full (or an explicit -processor). |
| 24 | Virtual threads no longer pinned by synchronized | A virtual thread blocking inside synchronized now releases its carrier thread. The Java 21 advice to prefer ReentrantLock for this reason no longer applies. |
| 24 | Security Manager permanently disabled | System.setSecurityManager always throws. It was already deprecated for removal in Java 17. |
| 24 | Class-File API (java.lang.classfile), ML-KEM and ML-DSA post-quantum crypto, AOT class loading | Mostly for tool and framework authors. |
| 24, 25 | Reader.of(CharSequence) (24), Reader.readAllLines() and readAllAsString() (25) | Small conveniences for character streams. |
| 25 | Key Derivation Function API, compact object headers as a product feature, generational Shenandoah | Security and performance, with no language change. |
Java 26 and 27: the releases after the LTS
Neither release is LTS. Oracle supports each one for six months until the next release. The next LTS is expected to be Java 29 in September 2027, following the two-year rhythm.
- Java 26 (March 17, 2026): HTTP/3 in
java.net.http.HttpClient. The Applet API is removed entirely. Changing afinalfield by deep reflection now produces warnings, to prepare for a later release that will forbid it ("final means final"). There are also more ahead-of-time cache improvements and better G1 throughput. - Java 27 (September 15, 2026): G1 is the default garbage collector in every environment, compact object headers are on by default, TLS 1.3 uses post-quantum hybrid key exchange by default, and JDK Flight Recorder can redact sensitive data. None of these changes the language.
Still in preview or incubation as of Java 27, and so not exam material:
- primitive types in patterns,
instanceofandswitch(fifth preview), for exampleo instanceof int i. It doesn't compile without--enable-preview. - structured concurrency (seventh preview)
- lazy constants (third preview; called "stable values" in Java 25)
- PEM encodings (third preview)
- the Vector API (twelfth incubator)
What's current
- This whole article is the "what's current" summary for the course. Java 25 is the current LTS. Java 27, from September 2026, is the newest release.
- Everything you learned for Java 21 still compiles on Java 25, with two kinds of exception. Programs that use
_as an ordinary name were already broken in Java 9, and removed APIs such as the Security Manager and applets are gone. - Use
javac --release 21to practise for 1Z0-830 and--release 25for 1Z0-831. The flag makes the compiler reject anything newer than that version, so the program below fails under--release 21with "module imports are not supported in -source 21".
Exam traps from this article
A complete example
The program below uses every final language and library feature from Java 22 to 25 in one class:
- a Markdown doc comment and a module import
- unnamed variables and patterns
- a flexible constructor that validates before
super()and sets a field the superclass constructor reads - all the built-in gatherers plus a custom one
- a scoped value
- off-heap memory with the FFM API
Reader.of,readAllLinesandIO.println
Unlike the other examples in this course, it's compiled with javac --release 25 -Xlint:all, with zero warnings, and run on JDK 25. It can't compile with --release 21.
import module java.base; // Java 25: every exported package of java.base
/// A tour of the language and library features finalized in Java 22 to 25.
///
/// This comment is a **Markdown** documentation comment (Java 23): `///` lines,
/// rendered by javadoc with Markdown syntax instead of HTML.
public class Solution {
// ---- Java 22: unnamed variables and patterns ------------------------------------
sealed interface Shape permits Circle, Square, Line { }
record Circle(double radius) implements Shape { }
record Square(double side) implements Shape { }
record Line(int x1, int y1, int x2, int y2) implements Shape { }
static String describe(Shape s) {
return switch (s) {
case Circle(var r) when r > 10 -> "big circle";
case Circle _, Square _ -> "round or square"; // several patterns, no bindings
case Line(var x1, _, var x2, _) -> "line spanning " + Math.abs(x2 - x1) + " columns";
};
}
// ---- Java 25: flexible constructor bodies ----------------------------------------
static class Account {
final String id;
Account(String id) {
this.id = id;
log("Account constructor sees id=" + id()); // overridable call: sees the subclass field
}
String id() { return id; }
}
static class SavingsAccount extends Account {
private final double rate;
SavingsAccount(String id, double rate) {
if (rate < 0 || rate > 0.2) throw new IllegalArgumentException("bad rate " + rate); // before super()
this.rate = rate; // assign own fields before super(): allowed now
super(id.strip().toUpperCase(Locale.ROOT));
}
@Override String id() { return super.id() + "@" + rate; }
}
static final List<String> LOG = new ArrayList<>();
static void log(String s) { LOG.add(s); }
// ---- Java 25: scoped values ----------------------------------------------------
static final ScopedValue<String> REQUEST_USER = ScopedValue.newInstance();
static String handle(String action) {
return REQUEST_USER.orElse("anonymous") + " -> " + action;
}
public static void main(String[] args) throws Exception {
System.out.println("== Java 22: unnamed variables and patterns");
for (Shape s : List.of(new Circle(12), new Square(3), new Line(2, 0, 9, 4))) {
System.out.println(" " + describe(s));
}
int count = 0;
for (var _ : List.of("a", "b", "c")) count++; // loop variable not needed
try {
Integer.parseInt("x7");
} catch (NumberFormatException _) { // exception not needed
System.out.println(" counted " + count + " items; the parse failed and we didn't need the exception");
}
Map<String, Integer> stock = new TreeMap<>(Map.of("fig", 3, "kiwi", 0));
stock.forEach((name, _) -> System.out.print(" " + name));
System.out.println();
System.out.println("\n== Java 25: flexible constructor bodies");
var acct = new SavingsAccount(" sv-17 ", 0.03);
System.out.println(" " + LOG.getFirst() + " (rate was set before super() ran)");
try {
new SavingsAccount("sv-18", 0.9);
} catch (IllegalArgumentException e) {
System.out.println(" validated before super(): " + e.getMessage());
}
System.out.println(" id=" + acct.id());
System.out.println("\n== Java 24: stream gatherers");
List<Integer> readings = List.of(3, 8, 5, 1, 9, 4, 7);
System.out.println(" windowFixed(3): " + readings.stream().gather(Gatherers.windowFixed(3)).toList());
System.out.println(" windowSliding(3): " + readings.stream().gather(Gatherers.windowSliding(3)).toList());
System.out.println(" scan running sum: " + readings.stream()
.gather(Gatherers.scan(() -> 0, Integer::sum)).toList());
System.out.println(" fold to a string: " + readings.stream()
.gather(Gatherers.fold(() -> "", (acc, n) -> acc + n)).findFirst().orElseThrow());
Gatherer<Integer, ?, Integer> increasesOnly = Gatherer.ofSequential(
() -> new int[] {Integer.MIN_VALUE},
(last, n, downstream) -> {
if (n > last[0]) { last[0] = n; return downstream.push(n); }
return true;
});
System.out.println(" custom gatherer (new highs): " + readings.stream().gather(increasesOnly).toList());
System.out.println("\n== Java 25: scoped values");
System.out.println(" outside: " + handle("browse"));
String inside = ScopedValue.where(REQUEST_USER, "mira").call(() -> handle("checkout"));
System.out.println(" inside: " + inside);
System.out.println(" bound after the call? " + REQUEST_USER.isBound());
System.out.println("\n== Java 22: foreign function & memory API (memory part)");
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(ValueLayout.JAVA_INT, 4); // off-heap int[4]
for (int i = 0; i < 4; i++) seg.setAtIndex(ValueLayout.JAVA_INT, i, (i + 1) * 11);
int sum = 0;
for (int i = 0; i < 4; i++) sum += seg.getAtIndex(ValueLayout.JAVA_INT, i);
System.out.println(" off-heap bytes=" + seg.byteSize() + ", sum=" + sum);
} // memory freed here, deterministically
System.out.println("\n== Java 24/25: small I/O additions");
try (Reader r = Reader.of("north\nsouth\neast")) { // Java 24
System.out.println(" Reader.of(...).readAllLines(): " + r.readAllLines()); // Java 25
}
IO.println(" IO.println works in any class too (Java 25)");
}
}
Output:
== Java 22: unnamed variables and patterns
big circle
round or square
line spanning 7 columns
counted 3 items; the parse failed and we didn't need the exception
fig kiwi
== Java 25: flexible constructor bodies
Account constructor sees id=SV-17@0.03 (rate was set before super() ran)
validated before super(): bad rate 0.9
id=SV-17@0.03
== Java 24: stream gatherers
windowFixed(3): [[3, 8, 5], [1, 9, 4], [7]]
windowSliding(3): [[3, 8, 5], [8, 5, 1], [5, 1, 9], [1, 9, 4], [9, 4, 7]]
scan running sum: [3, 11, 16, 17, 26, 30, 37]
fold to a string: 3851947
custom gatherer (new highs): [3, 8, 9]
== Java 25: scoped values
outside: anonymous -> browse
inside: mira -> checkout
bound after the call? false
== Java 22: foreign function & memory API (memory part)
off-heap bytes=16, sum=110
== Java 24/25: small I/O additions
Reader.of(...).readAllLines(): [north, south, east]
IO.println works in any class too (Java 25)
Points to notice:
case Circle _, Square _works because neither pattern declares a variable.Line(var x1, _, var x2, _)ignores two components.- The
Accountconstructor calls the overriddenid(), which readsrate. BecauseSavingsAccountassignedratebeforesuper(...), it prints@0.03instead of@0.0. - The invalid rate is rejected before any superclass code runs.
foldemits a single element, sofindFirst()gets it. The custom gatherer passes on only new highs (3, 8, 9).REQUEST_USERis bound only insidecall(...), andisBound()isfalseagain afterwards.- The off-heap
int[4]takes 16 bytes and is freed when theArenacloses, without waiting for the garbage collector.
Common questions
Should I take 1Z0-830 or 1Z0-831? If you're starting now and 1Z0-831 is offered to you, it certifies the current LTS. The extra material is what this article covers. Both certifications are valid, and Java 21 remains supported.
Do I need to learn the preview features? Not for either exam. It's still worth knowing their names so you can recognize them, especially primitive patterns and structured concurrency, which will probably be final in a future LTS.
Does IO.println replace System.out.println?
It's a convenience built on System.out, meant for beginners and small programs. Existing code and the exams still use System.out.
Are virtual threads different in Java 25?
The API is the same as in Java 21. The main change is that synchronized no longer pins a virtual thread to its carrier (Java 24), which removes the main reason to prefer ReentrantLock with virtual threads.
Summary
- Java 22 made
_an unnamed variable and pattern, finalized the FFM API and enabled multi-file source launch. - Java 23 added Markdown doc comments and withdrew string templates. Java 24 finalized stream gatherers and stopped
synchronizedfrom pinning virtual threads. - Java 25 (LTS, exam 1Z0-831) finalized flexible constructor bodies, module imports, compact source files with instance
mainmethods,java.lang.IOand scoped values. - Java 26 added HTTP/3, removed applets and started warning about final-field mutation. Java 27 changed JVM defaults (G1 everywhere, compact headers) and TLS.
- Primitive patterns, structured concurrency, lazy constants, PEM encodings and the Vector API are still preview or incubating features.
Practice quiz
Test yourself with the Java 22 to 25 quiz: 10 exam-style questions with explanations.
Previous: Java Files Advanced: Attributes, walk, find, lines and mark/reset (OCP 21)
Next: OCP Java 21 Final Review: Exam-Day Checklist and Mock Exams (OCP 21)
Related reading
- Java Files Advanced: Attributes, walk, find, lines and mark/reset (OCP 21)
- Java Console and User Interaction: System.in, System.out, System.err and Console (OCP 21)
- Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
- Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
- Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.