Command Palette

Search for a command to run...

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

Before Java 22: names for things you ignore

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?

Before Java 22: names for things you ignore
Sign in to run this example in your browser.

Expected output

items: 3
parsed 42
'4x2' is not a number
qty 10
qty 4
timer started
doing work
timer stopped