Java 21: Unnamed variables with underscore

Use _ for variables you must declare but never use, clarifying intent.

Code
var counts = new int[]{10, 20, 30};
int total = 0;
for (var _ : counts) {
    total += 5;   // we only care how many, not the value
}
System.out.println("total = " + total);
Output
total = 15
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26