Sub topic 1
Why Unused Variables Get in the Way
Prerequisites
You should know local variables, enhanced for loops, exceptions, and try-with-resources. You should also be familiar with var and Java 22 syntax.
Why unused variables get in the way
Java sometimes requires a declaration even when your code does not need the value. For example, a loop may need to run once for every element, but the element itself may not matter. A catch block may handle an exception without inspecting it.
A normal name suggests that the value has meaning:
for (String order : orders) {
total++;
}If order is never read, the name creates noise. Readers may wonder whether the code forgot to use it.
From identifier to error to feature: the underscore's history
Before Java 9, _ could be an ordinary identifier. Java 9 made a single underscore illegal as a normal identifier, leaving room for future language features. Java 22 gave _ a defined purpose through JEP 456: it marks a variable or pattern that the program intentionally does not use.
The feature makes intent visible:
flowchart TD
A[Unused value] --> B[Declare it with _]
B --> C[Compiler prevents accidental use]
C --> D[Code shows the value is irrelevant]Declaring an unnamed variable with _
An unnamed variable has no usable name. You can declare one with var _:
class Unnamed {
static int readValue() {
var _ = 42;
return 7;
}
}The compiler rejects any attempt to read _. This prevents the declaration from slowly becoming a misleading variable.
Unnamed locals, for loops, and try-with-resources
The most useful cases are repeated work and required resources:
import java.io.StringReader;
import java.util.List;
class Orders {
static int count(List<String> orders) {
int total = 0;
for (var _ : orders) {
total++;
}
try (var _ = new StringReader("input")) {
return total;
}
}
public static void main(String[] args) {
System.out.println(count(List.of("A", "B")));
}
}The loop variable is required by the enhanced for syntax, and the resource must be declared so Java can close it. Neither value is needed afterward.
Exercise
Why is _ clearer than naming the loop variable order when the loop only counts elements?
Show answer
It states that each element is intentionally ignored and prevents the value from being used accidentally.