Sub topic 11
Java versions, preview history, and migrating older code
This chapter covers which Java releases accept _ as an unnamed variable, why older code can't use it, and how to move existing code over without changing its behavior. It assumes you have read the earlier chapters on unnamed variables, unnamed patterns, and the restrictions on where _ is allowed. You should also know how to run javac and java from a terminal, or the equivalent settings in Maven or Gradle.
The timeline at a glance
The underscore went through three phases: a legal identifier, a reserved word that produced errors, and a language feature.
| Release | What `_` means | What you need |
|---|---|---|
| Java 1.0 to 7 | A normal identifier, like `x` or `count` | Nothing |
| Java 8 | Still an identifier, but the compiler warns | Nothing |
| Java 9 to 20 | Reserved. Using it as a name is an error | Rename the variable |
| Java 21 | Unnamed variable or pattern, as a preview feature | `--enable-preview` and `--release 21` |
| Java 22 and later | Unnamed variable or pattern, standard | Nothing special |
Java 25 is a long-term support (LTS) release. LTS releases receive updates for years, so many teams only move between them. If your team follows the LTS line and is on Java 21, Java 25 is the first LTS where this feature is standard. If you are on Java 17, the jump to 25 also brings record patterns and pattern matching for switch, which became final in Java 21.
Why Java 9 turned `_` into an error
In Java 8 and earlier, this was legal code:
int _ = 5;Java 8 added lambdas, and the language designers already planned to use _ for "a parameter I don't care about", as other languages do. To keep that door open, Java 8 warned about using _ as a name. Java 9 made it a compile error, so no new code could depend on the old meaning.
Between Java 9 and Java 20, _ therefore had no valid use at all. Every "unused" variable needed a throwaway name, and teams settled on conventions such as ignored, unused, or ex. Those names are the main thing you migrate.
Preview features in Java 21
A preview feature is a finished piece of the language that ships in a JDK release but stays off by default. The designers want real-world feedback before they freeze it. A preview feature can change or disappear in the next release.
Java 21 included unnamed patterns and variables as a preview (JEP 443). To use them on Java 21 you must pass the flag at both compile time and run time:
javac --release 21 --enable-preview Demo.java
java --enable-preview DemoWithout --enable-preview, the compiler rejects _ and reports that the feature is a preview feature that is disabled by default. The exact wording of the message varies, so read it for the words "preview" and "disabled".
Preview features have three side effects that matter in a build.
- The compiler marks the resulting class files as preview-dependent. Those classes load only on the same JDK feature release that compiled them, with
--enable-previewset. A class compiled with preview on Java 21 will not run on Java 22. - Libraries that you publish using preview features force every consumer to enable preview too. This is why library authors avoid previews.
- The
--releaseoption works with--enable-previewonly when the release number equals the JDK you are running. You cannot compile with--release 17and preview features together.
Java 22 finalized the feature in JEP 456, with the same behavior as the Java 21 preview. After that, code that compiled on Java 21 with --enable-preview compiles on Java 22 without any flag. You can remove the flag from your build and your launch scripts.
What changes in the compiled output
Nothing in the bytecode depends on whether a variable was unnamed. The compiler already assigns slots to local variables, and a variable without a name simply has no name entry in debug information. Two things follow.
- Runtime behavior is the same as with a named variable. A
catch (NumberFormatException _)catches exactly the same exceptions ascatch (NumberFormatException ignored). - Side effects in the initializer still run.
var _ = list.remove(0);removes the element. Only the storing of the result into a named variable goes away, so you can't read it later.
The version constraint is therefore on the class file version and the source level, not on library APIs. Compiling with --release 22 produces class files at version 66, which a Java 21 runtime rejects. If you must run on Java 21, you either stay with named variables or use the preview flag, with the restrictions above.
A step-by-step migration
Migrate only after your build uses Java 22 or later as the source level. The work comes in four passes, from safest to most judgment-heavy.
- Change the build to
--release 22(or later), and confirm the project compiles and tests pass before touching any code. - Fix any real use of
_as an identifier. This is rare, but very old code can contain it, and it is an error from Java 9. - Replace throwaway names in loops, catch blocks, lambdas, and try-with-resources.
- Simplify patterns: replace unused bindings with
Type _or with the bare_pattern, and mergeswitchcases that had identical bodies.
For step 1, a Maven build sets the release like this:
<properties>
<maven.compiler.release>22</maven.compiler.release>
</properties>Gradle users set options.release = 22 on the JavaCompile tasks. Both settings affect all modules, so check that every module in a multi-module build can move together.
Before and after
This class uses the older style. It counts lines, parses with a fallback, groups values, and describes shapes. Each marked spot has a named variable that is never read.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReportBefore {
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static int count(List<String> lines) {
int total = 0;
for (String ignored : lines) {
total++;
}
return total;
}
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException ignored) {
return fallback;
}
}
static Map<String, List<Integer>> group(List<String> keys, List<Integer> values) {
Map<String, List<Integer>> groups = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
groups.computeIfAbsent(keys.get(i), unused -> new ArrayList<>()).add(values.get(i));
}
return groups;
}
static int startX(Object o) {
if (o instanceof Line(Point(int x, int y), Point end)) {
return x;
}
return -1;
}
static String describe(Shape s) {
return switch (s) {
case Circle c -> "round";
case Square q -> "has corners";
case Triangle t -> "has corners";
};
}
public static void main(String[] args) {
System.out.println(count(List.of("a", "b", "c")));
System.out.println(parseOrDefault("x", 7));
System.out.println(group(List.of("a", "b", "a"), List.of(1, 2, 3)));
System.out.println(startX(new Line(new Point(4, 5), new Point(6, 7))));
System.out.println(describe(new Square(2)));
}
}This is the same class after migration. The main method is unchanged, so it is a direct check that the output stays the same.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReportAfter {
sealed interface Shape permits Circle, Square, Triangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Triangle(double base, double height) implements Shape {}
record Point(int x, int y) {}
record Line(Point start, Point end) {}
static int count(List<String> lines) {
int total = 0;
for (var _ : lines) {
total++;
}
return total;
}
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return fallback;
}
}
static Map<String, List<Integer>> group(List<String> keys, List<Integer> values) {
Map<String, List<Integer>> groups = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
groups.computeIfAbsent(keys.get(i), _ -> new ArrayList<>()).add(values.get(i));
}
return groups;
}
static int startX(Object o) {
if (o instanceof Line(Point(int x, _), _)) {
return x;
}
return -1;
}
static String describe(Shape s) {
return switch (s) {
case Circle _ -> "round";
case Square _, Triangle _ -> "has corners";
};
}
public static void main(String[] args) {
System.out.println(count(List.of("a", "b", "c")));
System.out.println(parseOrDefault("x", 7));
System.out.println(group(List.of("a", "b", "a"), List.of(1, 2, 3)));
System.out.println(startX(new Line(new Point(4, 5), new Point(6, 7))));
System.out.println(describe(new Square(2)));
}
}Both versions print the same five lines: 3, 7, {a=[1, 3], b=[2]} (the order of map entries may differ), 4, and has corners. Run both and compare the output. Note that the startX change dropped two bindings (y and end) and that describe now has two cases instead of three.
Pitfalls during migration
Do not rename a variable that is used. Only convert a name when the compiler would confirm that nothing reads it. If you replace a used name with _, the code fails to compile with a "cannot find symbol" style error. That error is useful: it tells you the variable was not unused after all.
Look for side effects before dropping a result. A statement like int result = service.call(); may have a result you ignore today. Converting it to var _ = service.call(); keeps the call. Replacing it with service.call(); also keeps the call. Both are safe, but never delete the call itself.
Merge switch cases only when the bodies match. Merging Square _, Triangle _ is correct only if both bodies were identical and neither used its binding. If either case read a field, keep the named binding and the separate case.
Be careful with catch blocks that hide errors. Migrating catch (Exception ignored) {} to catch (Exception _) {} makes an empty handler look deliberate. Keep a short comment or log call if the silence needs explaining.
Check your tooling. Older versions of formatters, linters, static analyzers, code generators, and IDE plugins use their own Java parsers. Some reject _ as a name or as a pattern. Upgrade these tools to releases that support Java 22 syntax before you migrate, or the build will fail even though javac is fine. Also check whether your linter has a rule against unused variables that now needs to recognize _.
Mixed source levels in one repository. If one module must stay on Java 17, do not use _ there. Keep a --release setting per module, and add a CI job that compiles each module at its own level so that a stray _ is caught early.
Deciding whether to migrate
Migration is optional. Code with ignored as a name compiles forever. The reasons to convert are consistency and signal: _ tells a reader and the compiler that the value is never read, and the compiler enforces it. The reasons to wait are an older minimum JDK, tools that can't parse the syntax yet, or a large codebase where a mass rewrite would obscure git blame. A reasonable compromise is to use _ in all new code once the build is on Java 22 or later, and convert old code only when you touch it for other reasons.
Exercise
Your project compiles with --release 21 --enable-preview, and you use catch (NumberFormatException _). You upgrade the build to JDK 22 with --release 22. What do you change in the build, and why can't you ship the Java 21 preview-compiled jar to a team that runs plain Java 22?
Show answer
Remove --enable-preview from the compile and run settings, and keep --release 22. The source code needs no change, because JEP 456 finalized the same behavior. The Java 21 jar cannot be shipped to plain Java 22 users because preview-compiled class files load only on the exact JDK feature release that compiled them (Java 21), and only with --enable-preview. Recompile the project with Java 22 and distribute that jar.
Exercise
A reviewer asks you to convert this to unnamed variables: for (String line : lines) { count++; } and case Square s -> "has corners"; case Triangle t -> "has corners";. Write the converted code and name one condition under which you should not merge the two case labels.
Show answer
Use for (var _ : lines) { count++; } and case Square _, Triangle _ -> "has corners";. Do not merge the labels if either body reads its binding, for example if the Square case uses s.side(), or if the two bodies differ. A merged case with unnamed patterns can't access any bindings.