Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Interview Questions Java Java and Cryptography Interview Series Java Programming Java Tutorial Module 27 - Java Advanced and JVM Internals

Java 21 Unnamed Variables and Patterns Underscore Syntax

Reviewed & accurate
AI Summary

Introduction

The Java 21 unnamed variables and patterns feature shipped in September 2023 as JEP 443 (preview) and was finalised in March 2024 as JEP 456 in Java 22. The feature was designed by Brian Goetz, Gavin Bierman, and the OpenJDK language team to remove the noise of unused variables and unused pattern bindings from Java source code. The underscore character _ had been a valid Java identifier since Java 1.0 (May 1996), but it had become a code smell because developers used it informally to mean "I am ignoring this value". Java 9 (September 2017) emitted a warning when _ was used as an identifier, Java 11 (September 2018) reclassified _ as a keyword so its use as an identifier became a compile error, and Java 21 finally gave _ a real meaning as the unnamed variable token.

For a Java learner, the Java 21 unnamed variables and patterns underscore syntax is the modern way to signal intent: when you write _, you tell the reader, the compiler, and any static analyser that you deliberately do not care about this value. Interviewers ask about it because it is the simplest entry point into the broader pattern-matching work that finalised in Java 21 (JEP 441) and Java 22 (JEP 456), and because it sits next to record patterns (JEP 440) and switch pattern matching as the third leg of the language story.

What is Java 21 Unnamed Variables and Patterns?

Java 21 unnamed variables and patterns is a language feature that introduces the underscore _ as a token that represents a variable or pattern component whose name does not matter. When _ appears on the left-hand side of an assignment, in a catch clause, in a try-with-resources header, in a lambda parameter list, in a for-each variable, or inside a record pattern, the compiler treats it as a fresh unnamed binding that cannot be referenced and that is dropped after the enclosing expression completes. Multiple _ in the same scope are allowed and each is treated as a distinct unnamed variable.

Java 21 unnamed variables belongs to the language syntax category, not the runtime category. It is a compile-time rewrite: the compiler emits the same bytecode as if you had named the variable _1, _2, _3 and never referenced them. The feature is different from C#'s discard pattern (var _) because Java's _ does not need var in front of it inside a lambda parameter list or a catch clause. It is different from Python's _ underscore because Python's _ is still a real variable that you can read, whereas Java's _ cannot be referenced at all.

How Java 21 Unnamed Variables Works - Step by Step

Step 1: The unnamed variable in catch. The catch clause has always required a variable name, even when the handler body ignores the exception. Before Java 21, the convention was catch (Exception ignored) or catch (Exception e) followed by an unused e. In Java 21 you can write catch (Exception _) { ... } to signal that the caught exception is intentionally dropped. The bytecode is identical to the named version, but the intent is unambiguous and static analysers like SpotBugs and Error Prone stop flagging the catch block as a swallowed exception.

Step 2: The unnamed variable in lambda parameters. A lambda with two parameters where one is unused had to be written as (k, v) -> useKey(k) before Java 21, which left v as a real binding the compiler tracked. In Java 21 the same code is (_, v) -> useKey(v) or (k, _) -> useKey(k). Both _ instances are unnamed and the compiler treats each as a distinct binding. If both lambda parameters are unused, you can write (_, _) -> 0; before Java 21 the same code was a compile error because each parameter had to have a unique name.

Step 3: The unnamed variable in side-effect assignments. A common pattern is to call a method purely for its side effect, such as queue.offer(x) which returns a boolean success flag that you intend to ignore. Before Java 21 you had to write boolean ignored = queue.offer(x); or just queue.offer(x); without any explicit signal. In Java 21 you can write var _ = queue.offer(x); to make the discard explicit. The var keyword is required here because the unnamed variable needs a declaration context.

Step 4: The unnamed pattern in record patterns. Record patterns (finalised in Java 21 as JEP 440) deconstruct a record into its components. When you only care about one component of a record, you can write case Point(int x, _) -> ... where the _ means "match any value for the y component but do not bind it". This is the unnamed pattern. It is more powerful than the unnamed variable because it does not even allocate a slot for the discarded component at runtime; the JIT can elide the load entirely.

Step 5: The unnamed pattern in type patterns. A type pattern case Box(_) matches a Box of any contained type and discards the binding. This is useful when you want to dispatch on the outer container type but do not need the inner value, for example case Optional<?>(_) -> "present" versus case Optional.empty -> "absent". The unnamed pattern combines with the type pattern to give a clean syntax for "match this type, ignore the value".

Step 6: The unnamed variable in nested record patterns. When deconstructing a nested record like Box<Pair<String, Integer>>, you might only care about the outer Box's existence and the inner Pair's first component: case Box(Pair(String s, _)) -> useString(s). Each _ is a distinct unnamed pattern that the compiler matches without binding. The compiler enforces that _ cannot be referenced from the case body.

Java Program for Java 21 Unnamed Variables

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;

public class UnnamedVariablesDemo {

    record Box<T>(T value, String tag) {}
    record Pair<T, U>(T first, U second) {}

    // Unnamed catch variable: the caught exception is intentionally dropped
    static int safeDivide(int[] values, int divisor) {
        int total = 0;
        for (int v : values) {
            try {
                total += v / divisor;
            } catch (ArithmeticException _) {
                // divisor was zero; skip this value silently
            }
        }
        return total;
    }

    // Unnamed pattern inside a record pattern
    static String describe(Box<Pair<String, Integer>> box) {
        return switch (box) {
            case Box(Pair(String s, _)) -> "first=" + s;
            case null -> "null";
        };
    }

    public static void main(String[] args) {
        // 1. Unnamed catch variable
        int result = safeDivide(new int[]{10, 20, 30}, 0);
        System.out.println("safeDivide with zero divisor: " + result);

        // 2. Unnamed lambda parameters (one of two)
        BiFunction<String, Integer, String> fn = (_, v) -> "value=" + v;
        System.out.println(fn.apply("ignored", 42));

        // 3. Unnamed var in side-effect assignment
        var _ = sideEffectCall();

        // 4. Unnamed pattern in record pattern deconstruction
        Box<Pair<String, Integer>> box =
            new Box<>(new Pair<>("hello", 99), "primary");
        System.out.println(describe(box));

        // 5. Two unnamed lambda parameters (both dropped)
        List<String> names = List.of("alice", "bob", "carol");
        names.forEach(_ -> System.out.println("tick"));

        // 6. Unnamed var in Map.forEach iteration
        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("x", 1);
        map.put("y", 2);
        map.put("z", 3);
        map.forEach((k, _) -> System.out.println("key=" + k));
    }

    static int sideEffectCall() {
        System.out.println("side-effect called");
        return 42;
    }
}

Code Explanation - Line by Line

The safeDivide method iterates an int array and accumulates the quotient of each element divided by the divisor. The try block calls v / divisor, which throws ArithmeticException when divisor is zero. The catch clause uses _ as the unnamed exception variable, signalling that the handler does not inspect the exception. The compiler emits the same try-catch bytecode as if the exception had a name; the only difference is the source-level intent.

The describe method uses a switch expression over a Box of Pair. The first case label uses a record pattern with a nested unnamed pattern: case Box(Pair(String s, _)) binds the inner Pair's first component to s and matches but does not bind the second component. The compiler validates that the deconstruction pattern matches the Box record's component types and the Pair record's component types. The null case is required because switch over Object is not exhaustive without it; the case Box(Pair(String s, _)) only covers non-null Box references.

The main method demonstrates six use cases. The first calls safeDivide with a zero divisor; the catch block swallows the three ArithmeticException instances silently. The second assigns a BiFunction whose first parameter is unused; the underscore signals that the first argument of the BiFunction is irrelevant. The third uses var _ = sideEffectCall() to call a method purely for its side effect; the result value is bound to an unnamed variable that the compiler immediately drops. The fourth creates a Box of Pair and passes it to describe, which deconstructs the nested record with the unnamed pattern. The fifth creates a List and calls forEach with a lambda that ignores its argument; the underscore signals that the consumer does not inspect the element. The sixth iterates a Map with forEach, discarding the value of each entry; the underscore signals that only the key matters.

Interview Questions and Answers

Q1. What is the underscore _ in Java 21 and what is it called?

The underscore _ in Java 21 is called the unnamed variable (or unnamed pattern when it appears inside a record pattern or type pattern). JEP 443 (preview, Java 21, September 2023) and JEP 456 (final, Java 22, March 2024) introduced it as a token that represents a binding the developer deliberately does not reference. It can appear in catch clauses, lambda parameters, side-effect assignments, try-with-resources headers, for-each variables, and inside record patterns.

Q2. Why was the underscore reclassified as a keyword in Java 11 before being given its new meaning in Java 21?

Java 9 (September 2017) emitted a warning when _ was used as an identifier, and Java 11 (September 2018) made _ a reserved keyword so its use as an identifier became a compile error. The OpenJDK team did this to clear the namespace for a future unnamed-variable feature: they wanted to remove the conflict between "developers informally using _ as a normal variable name" and "the future language meaning of _ as an unnamed binding". Java 21 finally gave _ its real meaning via JEP 443.

Q3. Can you write (_, _) -> 0 as a lambda in Java 21?

Yes. Two underscores in the same lambda parameter list are allowed and each is treated as a distinct unnamed variable. The lambda () -> 0 was the pre-Java-21 way to write a no-argument lambda, but (_, _) -> 0 documents explicitly that the lambda accepts two arguments and ignores both. This is useful for functional interfaces like BiFunction, BiPredicate, and BinaryOperator where the lambda must accept two arguments but the implementation does not use either.

Q4. What is the difference between an unnamed variable and an unnamed pattern?

An unnamed variable is a binding site (catch clause, lambda parameter, local variable declaration, try-with-resources, for-each) where the variable name is _. The compiler still allocates a slot for the value at runtime; it just does not let you reference it. An unnamed pattern is a pattern position inside a record pattern or type pattern (case Box(_), case Pair(String s, _)) where the underscore means "match any value but do not bind". The JIT can elide the load of an unnamed pattern component entirely because the value is never read.

Q5. Does using _ improve performance compared to a named variable that you never reference?

For unnamed variables in catch, lambda parameters, and side-effect assignments, the JIT already elides the load of unreferenced local variables through escape analysis and dead-code elimination, so there is no measurable runtime difference between _ and a named ignored variable. For unnamed patterns inside record patterns, the JIT can elide the component load entirely, which on tight loops over sealed hierarchies can produce a measurable speedup. The primary benefit is intent communication, not performance.

Q6. How do unnamed patterns interact with exhaustiveness in switch expressions over sealed hierarchies?

A case label that uses an unnamed pattern component still counts toward the exhaustiveness proof because the pattern matches any value of the component type. For example, switch over a sealed Shape hierarchy with case Circle(double r, _) and case Square(double side, _) is exhaustive over Shape because the unnamed _ pattern accepts any double in the second component. The compiler does not need to know the actual value to prove exhaustiveness; it only needs to know the type.

Q7. Your team is on Java 17 and a junior developer used _ as a variable name in production code. The compiler accepts it but you are planning a Java 21 migration. What is the migration risk and how would you handle it?

The risk is that _ was deprecated as an identifier in Java 9 and made a reserved keyword in Java 11, so the junior developer's code would not have compiled at all on Java 11 or later; if it compiles on Java 17, the team is actually on Java 8 or earlier. The correct migration is to first rename every existing _ identifier to a descriptive name before attempting to move to Java 11 or later, then upgrade to Java 21 where _ takes its new unnamed-variable meaning. The javac --release 9 flag emits a warning that catches any remaining _ uses during the migration.

Sample Input and Output

Input: int[] {10, 20, 30} with divisor 0,
       BiFunction (key, value) -> "value=" + value with apply("ignored", 42),
       Box(Pair("hello", 99), "primary"),
       List ["alice","bob","carol"] with forEach,
       Map {x=1, y=2, z=3} with forEach

Output:
side-effect called
safeDivide with zero divisor: 0
value=42
first=hello
tick
tick
tick
key=x
key=y
key=z

The output confirms six behaviours: the unnamed catch variable swallowed the three ArithmeticException instances silently; the unnamed lambda parameter let the BiFunction focus on the value only; the sideEffectCall ran and the result was discarded cleanly; the unnamed pattern in the record pattern deconstruction extracted only the first component of the inner Pair; the unnamed lambda parameter on forEach signaled intent to ignore the element; and the unnamed value parameter in Map.forEach printed only the keys.

Common Mistakes to Avoid

First, using _ as a variable that you actually intend to reference later. The compiler rejects any attempt to read the value of an unnamed variable: System.out.println(_) is a compile error. The _ token means "I will not read this", and the compiler enforces it.

Second, expecting _ to behave like a Python underscore that you can still read. In Python, _ is a regular variable; in Java, _ is a non-referenceable token. If you need the value later, give it a real name; do not use _ as a temporary scratch variable.

Third, mixing unnamed patterns with named patterns in non-final positions. A record pattern like case Pair(String s, Integer _) binds s but matches the second component without binding; if you intended to match without binding and then later use the value, you must use a named pattern (case Pair(String s, Integer i)) instead.

Fourth, forgetting that the underscore unnamed pattern only works inside record patterns and type patterns; you cannot use _ as a standalone pattern in a switch case label. case _ -> ... is a syntax error in Java 21; the equivalent is the default -> ... case label.

Real-World Applications

The Java 21 unnamed variables and patterns feature is the standard Java 21-and-later idiom for marking ignored values in source code. The JDK uses it in the java.util.concurrent.CompletableFuture exceptional completion handlers where the Throwable is often ignored, in the java.util.stream.Stream.collect combinators where downstream accumulator results are sometimes discarded, and in the java.lang.foreign.MemorySegment Scope callbacks where the segment's lifecycle is acknowledged but not inspected.

Reactive libraries Reactor and RxJava use the unnamed variable in their operator implementations: the onError handler in a Flux.subscribe often takes a Throwable that the handler logs elsewhere, so the parameter is _. Spring Framework 6 and Spring Boot 3 use the unnamed pattern in their AOP and interceptor chains where the target method's return value is sometimes matched but not bound. Annotation processing frameworks like Lombok and MapStruct use the unnamed pattern when generating code that deconstructs records; the generated case labels use _ for components that the generated code does not read.

Conclusion

Java 21 unnamed variables and patterns is a small but cleanly designed language feature: the underscore _ becomes the universal token for "this binding is intentionally ignored". The feature removes noise from catch clauses, lambda parameter lists, side-effect assignments, and record pattern deconstructions, and it pairs naturally with the JEP 440 record patterns and the JEP 441 pattern matching for switch. To go deeper, study JEP 443 (preview, Java 21) and JEP 456 (final, Java 22), then read the Gavin Bierman specification document for unnamed patterns, and after that the natural next topics are the record patterns (JEP 440) and the pattern matching for switch (JEP 441).

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments