Unnamed variables and patterns
suggest changeJava often makes you declare a variable you never use: the exception in a catch that only returns a default, the element in a loop that only counts, the key a Map.forEach lambda receives when you want the value. Since Java 22 (JEP 456) you can write _ instead of a name in those places. The same _ works inside record patterns, where it skips components you don't care about, and it makes it possible to list several patterns in one case.
The feature was a preview in Java 21 (JEP 443) and is final in Java 22, so it needs no flags on JDK 22 and later. The examples are single files you run with java Example.java. Output is from JDK 25.
This article covers:
- unnamed variables in
catch, loops, try-with-resources, locals and lambdas - the unnamed pattern
_and unnamed pattern variables likeCircle _ - several patterns in one
caselabel - what
_can't be used for, and when a name is still better
A bit of history
In Java 8 and earlier _ was a legal identifier, so int _ = 1; compiled. Java 8 warned about it, and Java 9 made _ a keyword that couldn't be used at all. That reserved it for this feature. With --release 8, JDK 25 still prints the old warning:
Old.java:3: warning: as of release 9, '_' is a keyword, and may not be used as an identifier
int _ = 1;
and with --release 21 (where the feature was still a preview):
Old.java:3: error: unnamed variables are not supported in -source 21
int _ = 1;
^
(use -source 22 or higher to enable unnamed variables)
An unnamed variable is declared but has no name, so nothing can read it. You can declare as many _ variables in one scope as you like, because they don't clash with each other.
Exception parameters
A catch block that handles an exception without looking at it is the most common case:
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
public class CatchExample {
static int parseOrDefault(String s, int fallback) {
try {
return Integer.parseInt(s.trim());
} catch (NumberFormatException | NullPointerException _) {
return fallback;
}
}
static boolean isDate(String s) {
try {
LocalDate.parse(s);
return true;
} catch (DateTimeParseException _) {
return false;
}
}
public static void main(String[] args) {
System.out.println(parseOrDefault(" 42 ", -1));
System.out.println(parseOrDefault("forty-two", -1));
System.out.println(parseOrDefault(null, -1));
System.out.println(isDate("2026-10-18") + " " + isDate("18.10.2026"));
}
}
42
-1
-1
true false
Before Java 22 you'd write catch (NumberFormatException e) or catch (NumberFormatException ignored). With _ the compiler guarantees the exception really isn't used, and readers don't have to scan the block to check. Multi-catch works the same way.
Be careful about which exceptions you swallow. _ makes it easy to write catch (Exception _) { }, which hides real bugs. The type in the catch still matters.
Loops
In an enhanced for loop, _ says "I care how many elements there are, not what they are". In a basic for loop, it can declare a variable whose initializer you need only for its side effect:
import java.util.List;
public class Loops {
public static void main(String[] args) {
List<String> cart = List.of("tea", "cake", "coffee");
int items = 0;
for (String _ : cart) {
items++;
}
System.out.println("items: " + items);
// repeat something n times
StringBuilder bar = new StringBuilder();
for (var _ : new int[5]) {
bar.append('#');
}
System.out.println(bar);
// a side-effecting initializer in a basic for loop
for (int i = 0, _ = startTimer(); i < 3; i++) {
System.out.println("step " + i);
}
}
static int startTimer() {
System.out.println("timer started");
return 0;
}
}
items: 3
#####
timer started
step 0
step 1
step 2
The counting loop is only an illustration; cart.size() is the real answer. The _ loop variable is useful when the collection doesn't know its size, for example an Iterable that reads from a file. For "repeat n times", a plain for (int i = 0; i < n; i++) is still clearer than allocating an array just to iterate it.
Record patterns are not allowed in the header of an enhanced for loop. That syntax was a preview in Java 20 and was removed in Java 21; see Destructuring.
Local variables with side effects
Sometimes you call a method only for what it does, but its result is the reason the call exists. Queue.remove() both removes and returns the head of the queue. If you only want to drop an element, you can call it as a statement, but var _ = shows that a value is being thrown away on purpose:
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
public class Locals {
public static void main(String[] args) {
Queue<String> lines = new ArrayDeque<>(List.of(
"name,qty", "apples,3", "pears,0", "plums,7"));
var _ = lines.remove(); // skip the CSV header
System.out.println(lines);
// keep x and z, drop y
Queue<Integer> coords = new ArrayDeque<>(List.of(1, 2, 3, 4, 5, 6));
while (coords.size() >= 3) {
int x = coords.remove();
var _ = coords.remove();
int z = coords.remove();
System.out.println("x=" + x + " z=" + z);
}
}
}
[apples,3, pears,0, plums,7]
x=1 z=3
x=4 z=6
The second loop shows why the name matters. Three calls to coords.remove() in a row look identical. Naming the first and third and using _ for the second shows the reader the layout of the data: x, (ignored), z.
An unnamed local variable must have an initializer. int _; on its own is a syntax error, because a variable that can never be assigned or read would be pointless.
try-with-resources
Some AutoCloseable objects are used only for the work they do when they are opened and closed: a timer that logs how long a block took, a lock holder, a temporary directory that deletes itself. The body never touches the resource, so its name is noise:
import java.util.concurrent.locks.ReentrantLock;
public class Resources {
// An AutoCloseable used only for its open/close side effects
record Timer(String name, long start) implements AutoCloseable {
static Timer start(String name) {
System.out.println("start " + name);
return new Timer(name, System.nanoTime());
}
@Override
public void close() {
System.out.println("end " + name);
}
}
record Held(ReentrantLock lock) implements AutoCloseable {
static Held acquire(ReentrantLock lock) {
lock.lock();
return new Held(lock);
}
@Override
public void close() {
lock.unlock();
}
}
static final ReentrantLock LOCK = new ReentrantLock();
static int counter;
public static void main(String[] args) {
try (var _ = Timer.start("load")) {
System.out.println("loading...");
}
try (var _ = Held.acquire(LOCK)) {
counter++;
System.out.println("locked: " + LOCK.isHeldByCurrentThread() + ", counter=" + counter);
}
System.out.println("locked: " + LOCK.isHeldByCurrentThread());
try (var _ = Timer.start("outer"); var _ = Timer.start("inner")) {
System.out.println("work");
}
}
}
start load
loading...
end load
locked: true, counter=1
locked: false
start outer
start inner
work
end inner
end outer
The last try declares two resources, both named _. They are still closed in reverse order. Before Java 22 you would have needed two different dummy names, and javac -Xlint:try warns that a named resource is never referenced in the body. With _ there is nothing to warn about.
Lambda parameters
A lambda has to accept every parameter the functional interface declares, even the ones it doesn't need:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Lambdas {
public static void main(String[] args) {
Map<String, Integer> stock = new TreeMap<>(Map.of("apples", 3, "pears", 0, "plums", 7));
// only the key is used
stock.forEach((name, _) -> System.out.print(name + " "));
System.out.println();
// computeIfAbsent passes the key, which we don't need
Map<String, List<String>> groups = new TreeMap<>();
for (String word : List.of("ant", "bee", "cat", "auk", "bat")) {
groups.computeIfAbsent(word.substring(0, 1), _ -> new ArrayList<>()).add(word);
}
System.out.println(groups);
// a stream index we don't need
String dashes = IntStream.range(0, 8).mapToObj(_ -> "-").collect(Collectors.joining());
System.out.println(dashes);
// ignore both arguments
BiFunction<String, Integer, String> constant = (_, _) -> "same";
System.out.println(constant.apply("x", 1));
// merge function that keeps the first value
Map<Integer, String> byLength = List.of("one", "two", "three", "four").stream()
.collect(Collectors.toMap(String::length, w -> w, (first, _) -> first, TreeMap::new));
System.out.println(byLength);
}
}
apples pears plums
{a=[ant, auk], b=[bee, bat], c=[cat]}
--------
same
{3=one, 4=four, 5=three}
computeIfAbsent(key, _ -> new ArrayList<>()) is probably the line you'll write most often. Before Java 22 people wrote k -> new ArrayList<>(), which makes a reader check whether k is used.
(_, _) -> "same" declares two unnamed parameters. Explicit types work too: (String _, Integer _) -> "same". You can't mix var and explicit types in one lambda, the same rule as before.
Unnamed patterns in record patterns
Record patterns (Java 21) make you list every component of the record. Often you only need one or two. _ on its own is the unnamed pattern: it matches any value of that component, including null, and binds nothing.
public class RecordPatterns {
enum Color { RED, GREEN, BLUE }
record Point(int x, int y) {}
record ColoredPoint(Point p, Color color) {}
record Line(ColoredPoint from, ColoredPoint to) {}
static String describe(Object o) {
return switch (o) {
case Point(var x, _) when x == 0 -> "point on the y axis";
case Point(var x, var y) -> "point " + x + "," + y;
case ColoredPoint(_, Color c) -> c + " point";
case Line(ColoredPoint(Point(var x1, _), _), ColoredPoint(Point(var x2, _), _)) ->
"line spanning x " + x1 + ".." + x2;
default -> "something else";
};
}
public static void main(String[] args) {
System.out.println(describe(new Point(0, 5)));
System.out.println(describe(new Point(2, 3)));
System.out.println(describe(new ColoredPoint(new Point(1, 1), Color.RED)));
System.out.println(describe(new Line(
new ColoredPoint(new Point(1, 9), Color.RED),
new ColoredPoint(new Point(4, 2), Color.BLUE))));
System.out.println(describe("hello"));
Object o = new ColoredPoint(new Point(7, 8), Color.GREEN);
if (o instanceof ColoredPoint(Point(int x, _), _)) {
System.out.println("x = " + x);
}
}
}
point on the y axis
point 2,3
RED point
line spanning x 1..4
something else
x = 7
In the Line case, a pattern with every component named would bind eight variables, six of them unused. With _ the pattern shows exactly which parts of the structure matter. The same works with instanceof, as the last lines show.
There are two forms:
_alone is the unnamed pattern. It can appear only as a component inside a record pattern. It doesn't check the type.Type _is a type pattern with an unnamed pattern variable. It checks the type but binds nothing. You can use it at the top level of acaseorinstanceof, or as a component.
case _ -> is not allowed; use default for "anything else". Likewise o instanceof _ is an error.
Several patterns in one case
Type patterns that bind nothing make it possible to put several patterns in one case label, the same way case 1, 2, 3 -> lists several constants (see Switch expressions). This is especially useful with sealed interfaces:
public class Shapes {
sealed interface Shape permits Circle, Square, Rectangle, Triangle {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double a, double b, double c) implements Shape {}
static int corners(Shape s) {
return switch (s) {
case Circle _ -> 0;
case Square _, Rectangle _ -> 4;
case Triangle _ -> 3;
};
}
static String kind(Shape s) {
return switch (s) {
case Square(_), Rectangle(_, _) -> "quadrilateral";
case Circle _, Triangle _ -> "other";
};
}
public static void main(String[] args) {
Shape[] shapes = {
new Circle(1), new Square(2), new Rectangle(2, 3), new Triangle(3, 4, 5)
};
for (Shape s : shapes) {
System.out.println(s + ": corners=" + corners(s) + ", " + kind(s));
}
}
}
Circle[r=1.0]: corners=0, other
Square[side=2.0]: corners=4, quadrilateral
Rectangle[w=2.0, h=3.0]: corners=4, quadrilateral
Triangle[a=3.0, b=4.0, c=5.0]: corners=3, other
case Circle _, Triangle _ -> "other" is better than default -> "other". Both switches are exhaustive without a default, so if you add a Hexagon to the sealed interface, the compiler reports every switch that doesn't handle it. A default would silently treat a hexagon as "other".
The rule: a case with several patterns must not declare any pattern variables. Each pattern can be a type pattern with _ or a record pattern whose components are all _ (or unnamed type patterns). Naming a variable gives an error:
case Square s, Rectangle r -> 1;
E2.java:6: error: illegal fall-through from a pattern
case Square s, Rectangle r -> 1;
^
(the current case label is missing a break)
The message is confusing, but the reason is simple: in the arm body, s would be unassigned when a Rectangle matched, and r when a Square matched. Even a variable with the same name and type in every pattern is rejected:
case Square(var side), Rectangle(var side, _) -> "side " + side;
E5.java:6: error: illegal attempt to redefine an existing match binding
case Square(var side), Rectangle(var side, _) -> "side " + side;
^
Write two cases, or call a method on a common supertype, when you need the values.
Guards apply to the whole label
A when guard after several patterns applies to all of them. Here's an event handler that mixes everything from this article:
import java.time.Instant;
public class Events {
sealed interface Event permits Click, KeyPress, Scroll, Resize {}
record Click(int x, int y, Instant at) implements Event {}
record KeyPress(char key, boolean shift, Instant at) implements Event {}
record Scroll(int delta, Instant at) implements Event {}
record Resize(int width, int height, Instant at) implements Event {}
static boolean debug = false;
static String handle(Event e) {
return switch (e) {
case KeyPress(char k, _, _) when k == 'q' -> "quit";
case KeyPress(char k, boolean shift, _) -> "type " + (shift ? Character.toUpperCase(k) : k);
case Click _, Scroll _ when debug -> "pointer event (debug): " + e;
case Click _, Scroll _ -> "pointer event";
case Resize(var w, var h, _) -> "resize to " + w + "x" + h;
};
}
public static void main(String[] args) {
Instant now = Instant.parse("2026-10-18T12:00:00Z");
Event[] events = {
new KeyPress('a', true, now), new KeyPress('q', false, now),
new Click(10, 20, now), new Scroll(-3, now), new Resize(800, 600, now)
};
for (Event e : events) {
System.out.println(handle(e));
}
debug = true;
System.out.println(handle(new Scroll(5, now)));
Object o = "text";
System.out.println(o instanceof String _);
}
}
type A
quit
pointer event
pointer event
resize to 800x600
pointer event (debug): Scroll[delta=5, at=2026-10-18T12:00:00Z]
true
Every event carries a timestamp that handle ignores, so each record pattern ends in _. The arm body can still refer to the selector e when it needs the whole object.
o instanceof String _ compiles, but it means the same as o instanceof String, so there's no reason to write it.
Where _ is not allowed
_ declares something that can't be referenced. It can't be used as an expression, and it isn't allowed in declarations that are part of an API:
public class E3 {
int _ = 1; // field
void f(int _) {} // method parameter
void g() {
int _; // no initializer
}
}
E3.java:2: error: underscore not allowed here
int _ = 1;
^
E3.java:3: error: underscore not allowed here
void f(int _) {}
^
E3.java:5: error: = expected
int _;
^
Reading an unnamed variable gives the same error:
var _ = args.length;
System.out.println(_);
E1.java:4: error: underscore not allowed here
System.out.println(_);
^
To sum up, _ can name:
- a local variable that has an initializer (including in a basic
forheader) - the variable of an enhanced
forloop - a resource in try-with-resources
- a
catchparameter - a lambda parameter
- a pattern variable (
Circle _), or a whole component pattern (_) inside a record pattern
It can't name fields, method or constructor parameters, record components, or the top-level pattern of a case or instanceof. Method parameters are excluded on purpose: they are part of the method's signature and show up in Javadoc and reflection, even when an override ignores them.
Readability guidance
- Use
_when ignoring a value is deliberate and obvious: acatchthat returns a fallback,computeIfAbsent(k, _ -> ...), a timestamp nobody inspects. - Keep the name if it documents something.
catch (InterruptedException e)followed byThread.currentThread().interrupt()doesn't neede, but a comment explaining why you don't rethrow matters more than the name. - Don't use
var _ = call();just to silence an IDE "result ignored" warning. If the result is an error code or abooleansuccess flag, check it. - In record patterns, use
_for the components you skip. If a pattern ends up with only_components,Type _is shorter:case Square _instead ofcase Square(_). - Prefer listing the remaining types with
case A _, B _ ->overdefaultwhen switching over a sealed type. You keep the compiler's exhaustiveness check. - If a pattern is mostly
_, you might want a method on the type instead.case Click _, Scroll _ -> "pointer event"repeated in five switches is a sign thatEventneeds anisPointer()method.
Summary
- Since Java 22,
_declares a variable or pattern that has no name and can't be read. It was a preview in Java 21. - Use it for unused
catchparameters, loop variables, resources, lambda parameters, and locals whose initializer has a side effect. Several_can share a scope. - Inside a record pattern,
_matches any component value without binding it.Type _checks the type without binding. - A
caselabel can list several patterns,case A _, B _ ->, as long as none of them binds a variable. Awhenguard applies to all of them. _is not allowed for fields, method parameters, as an expression, or ascase _.
More on the patterns themselves is in Pattern matching and Destructuring.