Sub topic 1
Why Unused Variables Get in the Way
Prerequisites
This chapter assumes you can read and write core Java: local variables, loops, and methods. You should know how try, catch, and try-with-resources work, and you should be comfortable with lambda expressions. You should also have seen records and basic instanceof and switch usage.
You do not need to know anything about unnamed variables yet. This chapter explains the problem they solve. Later chapters cover the syntax in detail.
The Rule That Causes the Problem
Java requires every variable to have a name. That rule is simple, and most of the time it costs nothing. You declare a variable because you want to use it later, so the name is useful.
Some constructs force you to declare a variable even when you have no use for it. The language demands a name, and the code that follows ignores it. The name still has to be chosen, written, read, and kept consistent. Each time, a reader sees a variable and has to check whether it matters.
This chapter looks at where this happens, what it costs, and the workarounds developers use today. Java 22 (JEP 456) adds a direct solution: write _ instead of a name. The chapter ends with a short preview of that solution.
Where Unused Variables Appear
Five situations produce unused variables again and again. All five are common in everyday code.
Loop Variables You Only Need to Count
The enhanced for loop must declare a loop variable. If you only want to run the body once per element, the element itself is irrelevant.
import java.util.List;
class Orders {
static int countOrders(List<String> orders) {
int total = 0;
for (String order : orders) {
total++;
}
return total;
}
}The variable order is declared and never read. The loop exists only to increment total. A reader has to scan the body to confirm that order plays no role.
Catch Parameters
Every catch clause declares an exception parameter. Often the handler does not care about the exception object. It only cares about the exception type.
class Parsing {
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return fallback;
}
}
}The handler returns fallback and never touches e. The type NumberFormatException carries all the meaning. The name e is noise.
Lambda Parameters
A lambda must accept every parameter that its functional interface declares. If the interface passes you a value you do not need, you still have to name it.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Grouping {
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), k -> new ArrayList<>()).add(values.get(i));
}
return groups;
}
}computeIfAbsent calls its function with the key. Here the function creates an empty list and does not need the key, so k is unused. This pattern is very common with computeIfAbsent, forEach on maps, and event handlers.
Record Pattern Components
Record patterns, introduced in Java 21, let you take a record apart in an instanceof test or a switch. A record pattern must account for every component of the record. If you want only one component, you still have to say something about the others.
record Point(int x, int y) {}
record Line(Point start, Point end) {}
class Geometry {
static int startX(Object o) {
if (o instanceof Line(Point(int x, int y), Point end)) {
return x;
}
return -1;
}
}The code needs only x. The pattern still declares y and end, and both go unused. The more components a record has, the worse this gets. A record with six components forces you to name six variables when you want one.
Type Patterns in Switch Cases
A type pattern such as Circle c declares a binding variable. When two cases produce the same result, you might want to combine them in one label. If each pattern declares a name, that does not work, because the names would conflict or leave some variables unassigned.
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 {}
class Describe {
static String describe(Shape s) {
return switch (s) {
case Circle c -> "round";
case Square sq -> "has corners";
case Triangle t -> "has corners";
};
}
}The bindings c, sq, and t are never used. Because each pattern declares a name, you cannot merge the last two cases into one label. You must repeat the right-hand side.
What It Costs You
An unused variable is a small defect. It has several concrete costs, and they add up across a large codebase.
- Reading cost. A named variable tells the reader "this value matters." When it does not, the reader wastes attention checking the body to confirm it. A misleading signal is worse than no signal.
- Naming cost. You must invent a name. Developers settle on
ignored,unused,ex,e,k,dummy, ornotUsed. These conventions differ between teams and even between files in the same project. - Warning noise. Compilers and static analysis tools flag unused locals. Javac's
-Xlinthas no general unused-variable check, but IDEs and tools such as Error Prone, SonarQube, and Checkstyle do. If you suppress these warnings, you may hide real mistakes. If you do not, the warnings pile up. - Maintenance risk. A variable that is "unused today" may get used later by accident, or someone may remove it and break a pattern or loop. The code does not say whether the omission was intentional.
- Blocked language features. Some forms, such as combining several type patterns in one
caselabel, only work when no pattern introduces a usable binding. A named but unused variable stops you from using them.
The point is not that these costs are large. Each one is small. The point is that they are pure overhead, because the program gains nothing from the name.
Workarounds Developers Use Today
Before Java 22, you had a few options. Each has drawbacks.
| Workaround | Example | Drawback |
|---|---|---|
| Short throwaway name | `catch (Exception e)` | The name still looks meaningful. Readers must check. |
| Descriptive "ignored" name | `catch (Exception ignored)` | Longer, and the convention varies by team. |
| Suppress the warning | `@SuppressWarnings("unused")` | Adds an annotation and can hide real problems. |
| Use the variable artificially | `Objects.requireNonNull(e)` | Adds code that has no purpose. |
| Restructure the code | Replace the loop with `list.size()` | Not always possible, and it can be less readable. |
The naming convention ignored is the most widespread. Some code uses __ (two underscores) or _1, _2 to suggest "I do not care". These are still ordinary identifiers. The compiler treats them as real variables, so two __ declarations in one scope clash.
Here is a catch block that uses the convention:
class Cleanup {
static void closeQuietly(AutoCloseable resource) {
try {
resource.close();
} catch (Exception ignored) {
// nothing useful to do here
}
}
}The name ignored documents intent, but only by agreement. The compiler does not check that ignored is really unused. Another developer could read it later and use it, and nothing would object.
Why a Language Feature Is the Right Fix
All the workarounds put the intent in a name or a comment. The compiler cannot verify names or comments. A language feature changes that: if the code says "this variable has no name", then the compiler knows it cannot be read, and readers know it too.
An unnamed variable gives these guarantees:
- The value cannot be used by accident, because there is no name to refer to it.
- The reader sees at once that the value is irrelevant.
- No naming convention is needed.
- Several unnamed variables can appear in the same scope without clashing, because none of them introduces a name.
The same idea extends to patterns. When a record component does not matter, a pattern can skip it entirely. When several cases share a result, patterns without bindings can share one label.
The line above is not a diagram. See the real diagram below.
A Preview of the Solution
With Java 22, each of the examples above can use _ in place of the unused name. This is only a preview. The following chapters explain each form, its rules, and its limits.
import java.util.List;
class OrdersPreview {
static int countOrders(List<String> orders) {
int total = 0;
for (var _ : orders) {
total++;
}
return total;
}
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException _) {
return fallback;
}
}
}In both methods the intent is part of the syntax. The loop variable and the exception parameter have no name, so neither can be read.
What Unnamed Variables Do Not Change
It helps to be clear about the limits before moving on. The feature solves one narrow problem. It does not remove the need to name variables that you use.
- The expression on the right of a declaration still runs. In a
try-with-resources or a local declaration with an initializer, the side effects happen even if you do not name the result. - An unnamed variable cannot be read. If you later need the value, you must give it a real name again.
- The feature does not remove the type from the declaration. In
catch (NumberFormatException _), the type still decides which exceptions the handler catches.
Keeping these points in mind will make the rules in later chapters easier to follow.
Exercise
A method has the loop for (String line : lines) { count++; }. Name two costs of leaving line as a named but unused variable, and state one reason a naming convention such as ignored does not fully fix the problem.
Show answer
Two costs: readers must check the loop body to confirm line is unused, and static analysis tools may warn about the unused variable. A convention such as ignored documents intent only by agreement. The compiler does not enforce that the variable stays unused, so someone could read it later without any error.
Exercise
In the record pattern o instanceof Line(Point(int x, int y), Point end), which variables go unused if the body only returns x, and why can you not simply leave them out before Java 22?
Show answer
The variables y and end go unused. A record pattern must have one sub-pattern for every component of the record, so before Java 22 you had to declare a named binding for each component even when you did not need it.