Sub topic 1
Why Unused Variables Get in the Way
Prerequisites
This chapter assumes you know the following:
- Core Java syntax: local variables, loops, and methods.
- Exceptions:
try,catch, andtry-with-resources. - Lambda expressions.
- Records and basic
instanceofandswitchusage.
You don't need to know pattern matching in depth yet. Later chapters review it.
The problem: syntax asks for a name you don't need
Java often requires you to declare a variable even when your code never reads it. The language needs the declaration to be well formed. Your program logic doesn't need it.
Three common cases:
- An enhanced
forloop must declare a loop variable, even if you only want to run the body once per element. - A
catchclause must declare an exception parameter, even if the handler ignores the exception. - A lambda must declare every parameter its functional interface defines, even if the body uses none of them.
Here is the first case in a complete program:
import java.util.List;
public class CountOrders {
static int countOrders(List<String> orders) {
int total = 0;
for (String order : orders) {
total++;
}
return total;
}
public static void main(String[] args) {
System.out.println(countOrders(List.of("a", "b", "c")));
}
}The variable order is declared and never used. The program prints 3, but a reader has to scan the loop body to confirm that order is ignored.
The same problem in catch blocks and lambdas
Catch parameters are the most common source of dead names. Many developers write e or ignored out of habit:
public class Parsing {
static int parseOrDefault(String text, int fallback) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return fallback;
}
}
public static void main(String[] args) {
System.out.println(parseOrDefault("42", -1));
System.out.println(parseOrDefault("forty-two", -1));
}
}Lambdas have the same issue. Map.computeIfAbsent passes the key to your function. Often you only want a fresh empty list:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public 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;
}
public static void main(String[] args) {
System.out.println(group(List.of("x", "y", "x"), List.of(1, 2, 3)));
}
}The parameter k is required by Function<K, V> but never used.
What an unused name costs
An unused variable looks harmless, but it has several costs:
- Reader doubt. A named variable suggests it matters. Readers check whether it is used, whether a bug dropped a use, or whether it has a side effect.
- Compiler and tool warnings. Many compilers, IDEs, and linters flag unused locals and parameters. Teams then add suppression annotations or rename variables to
ignoredto quiet the tools. Neither fix states the intent in the language itself. - Naming noise. Names like
ignored,unused,dummy, andignore2are inconsistent, and they stop you from reusing the same name twice in one scope. - Refactoring risk. If someone later starts using a variable called
ignored, the name now lies.
The next diagram shows why the compiler can't help you today. It can't tell the difference between "forgot to use this" and "deliberately not using this".
The direction Java takes
Java 22 (JEP 456) adds a way to say "I must declare something here, but I won't use it". You write a single underscore _ where the name would go. The loop above becomes for (var _ : orders), and the catch becomes catch (NumberFormatException _). The lambda becomes _ -> new ArrayList<>().
The idea is simple. Instead of inventing a throwaway name, you state in the language that the value is intentionally ignored. A reader knows immediately that nothing downstream depends on it. The compiler can also enforce that you never accidentally read it.
The same idea extends to patterns, where you match a structure but care about only some of its parts. The rest of this tutorial covers each place _ is allowed, where it is not, and when a real name is still the better choice.
Exercise
A method has the signature void log(String message) and contains catch (IOException e) { log("failed"); }. Which of the three costs from this chapter applies to e, and why does renaming it to ignored not fully solve it?
Show answer
Reader doubt and tool warnings apply: e suggests it matters, and many tools flag it as unused. Renaming it to ignored makes the intent clearer to humans, but it is only a convention. The language does not enforce it, so nothing stops someone from later reading ignored, and the name still occupies scope.