Unnamed variables and patterns: _
Since Java 22, a single underscore declares a variable or a pattern component you will not use. It tells readers and tools that ignoring the value is deliberate, it removes compiler warnings about unused resources, and it allows several patterns in one switch case. This page explains where _ is allowed and why, shows each use running, and shows the rules the compiler enforces.
Contents
What the underscore means
Java often requires a name for something you never read: the element of a loop that only counts, the exception in a catchignoredunused
Java 22 gave the single underscore two related meanings:
- An unnamed variable, as in
orfor (var _ : items) . It is declared, its initializer runs and the value is stored, but it has no name, so no code can read it. Several can appear in one scope.catch (Exception _) - An unnamed pattern, as in
. It matches any component value, includingcase Circle(_, double r) , and binds nothing.null is a type pattern with an unnamed binding: it tests the type without naming the value.Circle _
Because an unnamed pattern binds nothing, it also unlocked something new: several patterns in one casecase Circle _, Square _ ->
The underscore could be reused this way because it had been retired as a name. Java 8 warned when _
| Version | Status of _ |
|---|---|
| Java 1.0 to 7 | An ordinary identifier, like x |
| Java 8 | Still an identifier, with a warning that it will become a keyword |
| Java 9 to 20 | A keyword; any use is a compile error |
| Java 21 | Unnamed variables and patterns as a preview (JEP 443), with --enable-preview |
| Java 22 and later | Standard (JEP 456) |
All programs on this page were compiled and run on JDK 25 without any preview flags. On JDK 22, 23 or 24 they behave the same.
Unnamed variables
The program shows the five common places for an unnamed variable. Two of the three order IDs start with A and one with B, so the grouping in step 3 produces groups of different sizes.
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class UnnamedVariables {
static int parseOrZero(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException _) { // the exception object is not needed
return 0;
}
}
public static void main(String[] args) {
// 1. Enhanced for loop that only counts
List<String> orders = List.of("A-1", "B-7", "A-3");
int count = 0;
for (var _ : orders) {
count++;
}
System.out.println("orders counted: " + count);
// 2. catch parameter
System.out.println("parse \"42\" -> " + parseOrZero("42") + ", parse \"4x\" -> "
+ parseOrZero("4x"));
// 3. Lambda parameter required by the signature but not used
Map<String, Long> perPrefix = orders.stream()
.collect(Collectors.toMap(o -> o.substring(0, 1), _ -> 1L, Long::sum,
TreeMap::new));
System.out.println("orders per prefix: " + perPrefix);
// 4. A call made only for its side effect, with several _ in one scope
Queue<String> queue = new ArrayDeque<>(List.of("header", "skip-me", "data-1", "data-2"));
var _ = queue.remove(); // drop the header
var _ = queue.remove(); // a second _ is allowed: nothing is declared
System.out.println("remaining queue: " + queue);
// 5. Lambda with two parameters where only one matters
perPrefix.forEach((_, n) -> System.out.println(" a group of size " + n));
}
}
Output:
orders counted: 3
parse "42" -> 42, parse "4x" -> 0
orders per prefix: {A=2, B=1}
remaining queue: [data-1, data-2]
a group of size 2
a group of size 1
- The loop ran once per order, 3 times, without naming the element.
- The
needs only the exception type to decide: "4x" returned 0.catch requires a value function. Every order counts as 1 whatever its content, so the parameter istoMap , and the result is_ .{A=2, B=1} calls a method for its effect and shows the result is dropped on purpose. Two such declarations sit in one block, which with a real name would be a duplicate variable. The queue lost "header" and "skip-me".var _ = queue.remove()- In
only the value of each map entry is used, and the two group sizes printed.(_, n) -> ...
Unnamed patterns and multiple patterns per case
In a record pattern every component needs a pattern, even when only one matters. The program uses _
public class UnnamedPatterns {
sealed interface Shape permits Circle, Square, Rect, Line {
}
record Point(int x, int y) {
}
record Circle(Point center, double radius) implements Shape {
}
record Square(Point corner, double side) implements Shape {
}
record Rect(Point corner, double width, double height) implements Shape {
}
record Line(Point from, Point to) implements Shape {
}
// _ in a record pattern skips components you do not need
static double radiusOrSide(Shape s) {
return switch (s) {
case Circle(_, double r) -> r;
case Square(_, double side) -> side;
case Rect(_, double w, _) -> w;
case Line(Point(var x1, _), Point(var x2, _)) -> Math.abs(x2 - x1);
};
}
// Several patterns in one case are allowed when none of them binds a variable
static String dimension(Shape s) {
return switch (s) {
case Circle _, Square _, Rect _ -> "2D";
case Line _ -> "1D";
};
}
public static void main(String[] args) {
Point o = new Point(0, 0);
Shape[] shapes = {new Circle(o, 2.5), new Square(o, 3), new Rect(o, 4, 1),
new Line(new Point(1, 5), new Point(7, 5))};
for (Shape s : shapes) {
System.out.printf("%-7s %s main measure %.1f%n", s.getClass().getSimpleName(),
dimension(s), radiusOrSide(s));
}
}
}
Output:
Circle 2D main measure 2.5
Square 2D main measure 3.0
Rect 2D main measure 4.0
Line 1D main measure 6.0
skipped the centre and returned the radius 2.5.Circle(_, double r) skipped two of three components.Rect(_, double w, _) reached into both points, kept the x coordinates and ignored the y coordinates: |7 - 1| = 6.0.Line(Point(var x1, _), Point(var x2, _)) handles three record types in one case. In Java 21 this needed three separate cases with the same body, or acase Circle _, Square _, Rect _ -> "2D" , which would give up the exhaustiveness check.default- The switch in
is still exhaustive withoutdimension : the four type patterns cover the sealed interface.default
Resources, null components and side effects
Three details matter in real code. The program uses _null
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class UnnamedInPractice {
// An AutoCloseable used only for its open and close side effects
record Held(ReentrantLock lock) implements AutoCloseable {
static Held acquire(ReentrantLock lock) {
lock.lock();
System.out.println(" locked, hold count " + lock.getHoldCount());
return new Held(lock);
}
@Override
public void close() {
lock.unlock();
System.out.println(" unlocked, hold count " + lock.getHoldCount());
}
}
record Point(int x, int y) {
}
record Pin(Point at, String label) {
}
static String describe(Object o) {
return switch (o) {
case Pin(Point(var x, _), var label) -> label + " at x=" + x;
case Pin(_, var label) -> label + " with no position";
default -> "something else";
};
}
static int nextId(List<String> log) {
log.add("nextId called");
return 42;
}
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
System.out.println("try-with-resources with _:");
try (var _ = Held.acquire(lock)) {
System.out.println(" working while locked: " + lock.isHeldByCurrentThread());
}
// _ matches null components; a nested record pattern does not
System.out.println(describe(new Pin(new Point(3, 4), "home")));
System.out.println(describe(new Pin(null, "draft")));
// The initializer of an unnamed variable is still evaluated
List<String> log = new ArrayList<>();
var _ = nextId(log);
System.out.println("side effects kept: " + log);
}
}
Output:
try-with-resources with _:
locked, hold count 1
working while locked: true
unlocked, hold count 0
home at x=3
draft with no position
side effects kept: [nextId called]
- The lock was held inside the block and released at the end: hold count 1, then 0. The resource exists only for its
. With a named variable,close() warns "auto-closeable resource r is never referenced in body"; withjavac -Xlint:try there is no warning, because not referencing it is the declared intent._ - The pin "draft" has a
position. It did not matchnull , because a nested record pattern never matchesPin(Point(var x, _), var label) . It did matchnull , because the unnamed pattern matches anything,Pin(_, var label) included.null still calledvar _ = nextId(log) , and the log shows it. An unnamed variable drops the name, not the evaluation.nextId
Trap: an unnamed catch that hides bugs
catch (Exception _)30s
import java.util.Map;
public class CatchTrap {
static final Map<String, String> SETTINGS = Map.of("port", "8080", "timeout", "30s");
// Too broad: catch (Exception _) also hides the bug of asking for a missing key
static int broad(String key) {
try {
return Integer.parseInt(SETTINGS.get(key).strip());
} catch (Exception _) {
return -1;
}
}
// Narrow: only the expected failure is ignored, everything else still surfaces
static int narrow(String key) {
try {
return Integer.parseInt(SETTINGS.get(key).strip());
} catch (NumberFormatException _) {
return -1;
}
}
public static void main(String[] args) {
for (String key : new String[] {"port", "timeout", "prot"}) {
String result;
try {
result = String.valueOf(narrow(key));
} catch (NullPointerException e) {
result = "NullPointerException (the key is missing)";
}
System.out.printf("%-8s broad=%-3d narrow=%s%n", key, broad(key), result);
}
}
}
Output:
port broad=8080 narrow=8080
timeout broad=-1 narrow=-1
prot broad=-1 narrow=NullPointerException (the key is missing)
- Both versions read 8080 for "port" and returned -1 for "timeout", the case the code was written to handle.
- For the misspelled "prot",
returnedSETTINGS.get andnull threwstrip() . The broad version swallowed it and returned -1, exactly as if the value had been malformed, so the typo would go unnoticed in production. The narrow version let the exception through.NullPointerException - Use
only for the exception type you have decided to ignore, and keep a name, and a log statement, for anything else. A multi-catch such as_ is allowed when several expected types need the same handling.catch (NumberFormatException | DateTimeParseException _)
What the compiler allows and rejects
The program compiles eight small classes in memory with the javax.tools--release 8--release 9
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
// Compiles small classes in memory and prints javac's verdict on each use of _
public class UnderscoreRules {
public static void main(String[] args) {
check("8", "_ as an ordinary name, Java 8", "void m() { int _ = 1; int y = _ + 1; }");
check("9", "_ as an ordinary name, Java 9", "void m() { int _ = 1; }");
check("25", "reading an unnamed variable", "void m() { int _ = 1; int y = _ + 1; }");
check("25", "unnamed field", "int _ = 1;");
check("25", "unnamed method parameter", "void m(int _) { }");
check("25", "two bindings in one case", "record A(int x) {} record B(int x) {}"
+ " int m(Object o) { return switch (o) { case A(int x), B(int x) -> x;"
+ " default -> 0; }; }");
check("25", "_ as a whole case label", "int m(Object o) {"
+ " return switch (o) { case _ -> 0; }; }");
check("25", "unused lambda parameters", "java.util.function.BiFunction<String,"
+ " Integer, Integer> f = (_, _) -> 0;");
}
static void check(String release, String label, String members) {
String source = "class T { " + members + " }";
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
JavaFileObject file = new SimpleJavaFileObject(
URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
};
List<String> options = List.of("--release", release, "-Xlint:-options", "-d",
System.getProperty("java.io.tmpdir"));
boolean ok = javac.getTask(null, null, diags, options, null, List.of(file)).call();
System.out.println(label + ": " + (ok ? "compiles" : ""));
for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
String text = d.getMessage(Locale.ENGLISH).strip();
System.out.println(" " + d.getKind().toString().toLowerCase(Locale.ROOT) + ": "
+ String.join(" ", text.split("\\s*\\n\\s*")));
}
}
}
Output:
_ as an ordinary name, Java 8: compiles
warning: as of release 9, '_' is a keyword, and may not be used as an identifier
warning: as of release 9, '_' is a keyword, and may not be used as an identifier
_ as an ordinary name, Java 9:
error: unnamed variables are not supported in -source 9 (use -source 22 or higher to enable unnamed variables)
reading an unnamed variable:
error: underscore not allowed here
unnamed field:
error: underscore not allowed here
unnamed method parameter:
error: underscore not allowed here
two bindings in one case:
error: illegal attempt to redefine an existing match binding
_ as a whole case label:
error: underscore not allowed here
unused lambda parameters: compiles
- With
,--release 8 worked as an ordinary name, read and all, with two warnings that it would become a keyword. With_ it is an error; the current compiler's message points to Java 22 for the new meaning.--release 9 - An unnamed variable can never be read:
is "underscore not allowed here"._ + 1 - Fields and method parameters cannot be unnamed. They are part of a class's API, where a name documents the meaning even if this implementation ignores the value.
- Two record patterns that both bind
cannot share a case, even with the same name and type: "illegal attempt to redefine an existing match binding". Only unnamed bindings can be combined.x on its own is not allowed; usecase _ . The unnamed pattern exists only inside record patterns.default- A lambda may have several
parameters, as in_ .(_, _) -> 0
Where _ can appear
| Place | Example | Typical reason |
|---|---|---|
| Local variable | var _ = queue.remove(); | Call made only for its side effect |
Enhanced for | for (var _ : items) | Counting or repeating |
Basic for | for (int i = 0, _ = sideEffect(); i < n; i++) | Rare: an initializer run once |
catch | catch (NumberFormatException _) | Type is enough to decide |
| Lambda parameter | (_, value) -> ... | Signature demands a parameter |
| try-with-resources | try (var _ = lock.acquire()) | Resource used only for open and close |
| Record pattern component | Circle(_, double r) | Component not needed |
| Type pattern | case Line _ -> | Type matters, value does not |
When to use it, and when not
| Situation | Use |
|---|---|
| The value is truly irrelevant | _ |
| The exception should be logged or wrapped | A name: swallowing it with _ |
| Several record types share one branch | case A _, B _ -> |
| Most components of a large record are ignored | A type pattern plus accessors may read better than many _ |
| Code must compile on Java 21 or older | A descriptive name such as ignored |
| A method parameter you do not use | A name; _ |
The underscore builds on