Command Palette

Search for a command to run...

Back to the lesson: Topic 11.4 — Unnamed Variables and Patterns
Core Java · Example 2 of 2 Java 21+

Java 21: unused components still need names

From Java 22 you can write _ instead of a name for a variable or pattern you must declare but never use: catch (NumberFormatException _), (_, v) -> ..., case Point(var x, _). It tells readers and the compiler "this is deliberately ignored", and it can't be read by mistake.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using JDK 22+ syntax, rewrite for (int i = 0; i < 3; i++) { System.out.println("hi"); } as an enhanced for over List.of(1, 2, 3) with an unnamed loop variable, and say what it prints.

02

Given record Order(String id, String customer, int totalPaise), write a Java 22 switch that returns "big" when totalPaise > 100000 and "normal" otherwise, using _ for the two unused components. Then write the Java 21 equivalent and run it.

03

Write a Map<String, Integer> with three entries in a TreeMap and print only the values using forEach with an unnamed key parameter (Java 22). Give the Java 17 version too.

Explain it without notes

01

Where can _ be used as an unnamed variable, and where can't it?

02

What is the difference between an unnamed pattern variable (Circle _) and the unnamed pattern (_)?

03

Why are multiple patterns in one case allowed only when none binds a variable?

04

Why did Java make _ a keyword in Java 9, years before this feature?

Java 21: unused components still need names Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

click at 10,20
right click at 5,5
key A
key b
scroll up
window changed