Sub topic 12
When to use `_` and when to keep a name
This chapter assumes you know the following from earlier chapters:
- Unnamed variables in locals, loops,
catchblocks, try-with-resources and lambdas. - Type patterns and record patterns.
- The difference between an unnamed pattern variable (
Type _) and the unnamed pattern (_). - The places where
_is not allowed.
You can already write all of these forms. This chapter covers the judgment calls: when _ helps the reader, when it hides something they need, and how tools and team rules can enforce the decision.
What `_` communicates
A name tells the reader what a value is. _ tells the reader that the value does not matter here. The compiler enforces that claim. Nothing can read an unnamed variable, so a later edit cannot start using it by accident.
That gives _ a specific job. Use it when "this value is irrelevant" is true and worth saying. Do not use it just because you are in a hurry to avoid picking a name.
Compare these two methods:
import java.util.List;
public class Counting {
static int countWithName(List<String> items) {
int total = 0;
for (String item : items) {
total++;
}
return total;
}
static int countWithUnderscore(List<String> items) {
int total = 0;
for (var _ : items) {
total++;
}
return total;
}
public static void main(String[] args) {
List<String> items = List.of("a", "b", "c");
System.out.println(countWithName(items));
System.out.println(countWithUnderscore(items));
}
}In the first method a reader must scan the loop body to confirm that item is never used. In the second method the declaration already says so. This is the strongest case for _: the language forces you to declare something, and you have nothing useful to call it.
Cases where `_` is the better choice
Loop variables that only count iterations
An enhanced for loop requires a variable. If the body only repeats an action or counts, var _ is accurate. If the loop is really "do this N times", an indexed loop or IntStream.range is often clearer than iterating a collection you do not read.
Lambda parameters that a framework forces on you
APIs such as computeIfAbsent, Map.forEach and reduce pass arguments you may not need. Here _ shows which parameters matter:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Index {
public static void main(String[] args) {
Map<String, List<Integer>> index = new TreeMap<>();
String[] keys = {"a", "b", "a"};
int[] values = {1, 2, 3};
for (int i = 0; i < keys.length; i++) {
index.computeIfAbsent(keys[i], _ -> new ArrayList<>()).add(values[i]);
}
index.forEach((key, _) -> System.out.println(key));
int count = index.values().stream().reduce(0, (acc, _) -> acc + 1, Integer::sum);
System.out.println(count);
}
}The computeIfAbsent lambda ignores its key, which is the usual case. The forEach lambda uses the key and ignores the value. You can use _ several times in one parameter list, which named parameters would not allow.
Catch parameters in deliberate fallbacks
Use _ when the exception type is the whole story:
public class Parse {
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return fallback;
}
}
public static void main(String[] args) {
System.out.println(parseOrDefault("42", 0));
System.out.println(parseOrDefault("forty-two", 0));
}
}The method's contract is "bad input yields the fallback". The exception object carries no information the caller needs.
Record patterns that care about only some components
When a pattern is about the shape of the data, ignoring components keeps the pattern short. The unnamed pattern _ is shorter than repeating each component's type and also matches any component, so the pattern does not depend on component types you do not care about.
Switch cases that share a result
case Login _, Logout _ -> is a clear statement that two types are handled identically. It also means the branch cannot use either value.
Cases where a name is better
The value could help with debugging
An exception is the main example. catch (IOException _) that returns a default silently removes the evidence of what went wrong. If anyone might need that evidence later, keep the name and use it:
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Config {
static String load(Path path) {
try {
return Files.readString(path);
} catch (IOException e) {
throw new UncheckedIOException("cannot read " + path, e);
}
}
public static void main(String[] args) {
try {
load(Path.of("does-not-exist.properties"));
} catch (UncheckedIOException e) {
System.out.println(e.getMessage());
}
}
}Here e is used as the cause, so a name is required. Even when you do not use the exception today, ask whether a log line would help later. If it would, use a name and log it.
The name documents something the type does not
In (a, b) -> a.compareTo(b) the names are fine. In (_, b) -> b, the underscore makes it obvious that the first argument is skipped. But consider Map.merge(key, value, (old, fresh) -> fresh). The names old and fresh explain the policy, even though old is unused. In that case, (_, fresh) -> fresh is still acceptable. Choose whichever makes the intent clearer, and apply the same choice consistently in one codebase.
The ignored value is a side effect you rely on
var _ = compute(); still evaluates compute(). The initializer runs, and only the result is discarded. This is legal and sometimes right, for example try (var _ = lock.acquire()). A plain call statement is clearer when you do not need a try-with-resources scope. Do not write var _ = list.remove(0); to silence an unused-result warning when a plain statement list.remove(0); is equivalent and simpler.
Too many underscores
A lambda with (_, _, _, d) -> d or a record pattern with five wildcards usually means the code is matching too deeply into the data. Consider adding an accessor, extracting a method, or choosing a smaller pattern.
A decision guide
The diagram summarizes the questions to ask, in order.
Patterns and switch: a worked example
This program uses _ in all three pattern positions you have seen: Type _ in a shared case, _ in a record component, and a named binding where the value is used.
public class Review {
sealed interface Event permits Login, Logout, Purchase {}
record Login(String user, long at) implements Event {}
record Logout(String user, long at) implements Event {}
record Purchase(String user, int cents, String sku) implements Event {}
static String describe(Event e) {
return switch (e) {
case Login _, Logout _ -> "session event";
case Purchase(_, int cents, _) -> "purchase of " + cents + " cents";
};
}
public static void main(String[] args) {
System.out.println(describe(new Login("ana", 1L)));
System.out.println(describe(new Logout("ana", 2L)));
System.out.println(describe(new Purchase("ana", 499, "X-1")));
}
}Two points are easy to miss:
case Login _, Logout _is only legal because neither pattern declares a named binding. Writingcase Login l, Logout _is a compile error.- If you later need the user name in the first branch, you must split the case, because a shared case cannot bind anything. That change is a signal that the two types were never truly identical. It is not a reason to avoid sharing in the first place.
Tooling and enforcement
The compiler does not warn about unused locals, and _ is optional everywhere it is allowed. Style is enforced by other tools.
| Tool | What it can do | Notes |
|---|---|---|
| IDE inspections | Flag unused variables, loop variables and lambda parameters, and often offer a quick fix that replaces the name with `_` | Check that the inspection is set to Java 22 or later, or the fix may not appear |
| Error Prone | The `UnusedVariable` check reports unused locals and parameters | It treats names that start with `unused` as intentional, so decide whether to keep that convention or migrate to `_` |
| Checkstyle, PMD, SpotBugs | Rules for unused variables and for empty catch blocks | Empty `catch (X _) {}` is still an empty catch block, so a rule against empty catch blocks continues to apply |
| Code review | Judges whether ignoring a value is justified | Tools cannot tell whether an exception should have been logged |
Migrating existing code is mostly mechanical. Rename unused, ignored or ignore variables to _, but only when the project builds with Java 22 or later (Java 21 accepts it only as a preview feature). Review each empty catch block separately. Replacing ignored with _ does not make a swallowed exception acceptable. It only removes the one hint that someone chose to swallow it.
A practical team convention:
- Use
_for loop variables, lambda parameters and pattern components that are irrelevant. - Use
_in a catch block only when the fallback is the documented behavior, and add a short comment if the reason is not obvious. - Keep a name when the value is used, or when logging it would help.
- Prefer
Type _in shared switch cases only when the branches are truly identical.
Common mistakes
- Using
_as a way to hide a design problem. Many unused parameters can mean the method has the wrong signature. - Assuming
_makes code faster or safer. It changes readability only. The initializer, if any, still runs. - Mixing styles in one file. One lambda uses
ignoredand the next uses_. Pick one. - Targeting the wrong Java version.
_as an identifier was a warning in Java 8 and an error from Java 9, and unnamed variables became final in Java 22. A build that targets an older release rejects the new syntax.
Exercise
Look at this method. Which of the three catch parameters, if any, should become _, and which should keep a name? Explain each choice.
try { return Integer.parseInt(text); } catch (NumberFormatException e) { return 0; }
try { return Files.readString(path); } catch (IOException e) { throw new UncheckedIOException(e); }
try { cache.refresh(); } catch (RuntimeException e) { }
Show answer
The first can become _, because the contract is "invalid input yields 0" and the exception carries nothing the caller needs. The second must keep its name, because e is passed as the cause. The third should not simply become _. It swallows every runtime exception from refresh, so it should at least log the exception, which requires a name. Replacing e with _ would hide the problem without fixing it.
Exercise
A switch has case Circle c, Square _ -> "shape";. Why does it fail to compile, and what are two valid ways to fix it?
Show answer
A case label with several patterns cannot declare any named binding, and c is one. Fix 1: change it to case Circle _, Square _ -> "shape"; if the branch does not use the circle. Fix 2: split it into case Circle c -> ... and case Square _ -> ... if the circle's value is needed.