Sub topic 12
When to use _ and when to keep a name
This chapter assumes you know the Java 22 forms of _: unnamed local variables, loop variables, catch and lambda parameters, unnamed pattern variables (Type _), and the unnamed pattern (_) inside record patterns. It also assumes you can read switch with record patterns. The question here is not whether _ compiles. The question is whether it makes the code easier to read.
The core rule
_ tells the reader, and the compiler, that a value exists but is deliberately ignored. A name says the opposite: this value matters here. Use _ when the declaration is required by the syntax and nothing in the code needs the value. Keep a name when it explains the code, even if you don't use the variable yet.
record Order(String id, int quantity, String note) {}
class Bulk {
static boolean isBulk(Object o) {
return o instanceof Order(_, int q, _) && q >= 100;
}
}Here the reader sees at once that only quantity matters. Naming id and note would add two names that nothing uses.
Good uses
- Loops that only count or repeat.
for (var _ : orders)shows that the element is irrelevant. - Catch blocks that recover without the exception.
catch (NumberFormatException _)makes it clear you chose not to inspect the cause. - Lambdas that ignore their argument.
computeIfAbsent(key, _ -> new ArrayList<>())avoids a throwaway name likek. - Record patterns that need one or two components. Use
_for the rest. - Switch cases that share a result.
case Square _, Triangle _ -> ...lets one label cover several types.
Cases where a name is better
Keep the name when it carries information the code does not show.
- Exceptions you may need later. An empty
catch (IOException _)that swallows an error hides a problem. If the handler logs, wraps, or rethrows, you need the variable. - Record components whose meaning helps the reader. A pattern such as
Line(Point(int x, _), _)is short, but if the pattern has four or five components,_everywhere can leave the reader counting positions. Names likeOrder(String id, int quantity, String note)document the shape. - Variables you plan to use soon. Do not use
_as a placeholder you will rename later. - Method parameters. Java does not allow
_here, so name the parameter even if an implementation ignores it.
| Situation | Prefer | Reason |
|---|---|---|
| Loop counts elements only | `var _` | Element has no role |
| Catch block returns a fallback | `_` | Cause is not inspected |
| Catch block logs or wraps | Named | Cause is needed |
| Record pattern, one component used | `_` for the others | Highlights the used one |
| Record with many similar components | Named or `var` | Position alone is hard to read |
| Overriding a method, ignoring a parameter | Named | `_` not allowed for parameters |
Deciding quickly
Tooling and team conventions
The compiler does not warn about unused variables, so _ does not change compile results. Its value is in the signal to humans and tools. Many IDEs and linters flag unused locals and catch parameters, and _ tells them the omission is intentional. Check that your tools understand Java 22 syntax before adopting _ widely. On older versions such as Java 21, the feature was a preview and needed --enable-preview. On Java 8 and earlier, _ was a legal identifier. Since Java 9 it has been an error.
Agree on a team rule and apply it consistently. A common one: use _ for ignored loop elements, lambda arguments, and pattern components, and require names for exceptions that are swallowed or logged. Review comments are the place to catch a lazy _ that hides a decision, such as an empty catch block.
import java.util.logging.Logger;
class Reader {
private static final Logger LOG = Logger.getLogger(Reader.class.getName());
static int parsePort(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
LOG.warning("Bad port '" + text + "': " + e.getMessage());
return 8080;
}
}
}This handler uses e, so a name is required. If the handler only returned the default quietly, _ would be the honest choice.
Exercise
A colleague rewrites catch (IOException e) { log.error("read failed", e); } as catch (IOException _) { log.error("read failed"); }. Is this a good use of _? Explain.
Show answer
No. The original handler used e to record the stack trace and cause. The rewrite compiles, but it throws away diagnostic information that the code previously preserved. _ fits only when the exception is truly irrelevant, such as returning a fallback value from a failed parse.
Exercise
Rewrite static boolean isEmpty(Object o) { return o instanceof Box(Object content) && content == null; } so it matches the case when you do not care about the content, but name one thing you must not change about the pattern.
Show answer
If the content is not needed, you cannot just use _ as the whole pattern, because a top-level _ is not allowed. The record pattern must stay: o instanceof Box(_). That checks only that o is a Box. It no longer tests whether content is null, so the null check needs a name and the original code was already correct.