Unnamed variables and patterns: _

Since Java 22, a single underscore declares a variable or a pattern component you will not use. It tells readers and tools that ignoring the value is deliberate, it removes compiler warnings about unused resources, and it allows several patterns in one switch case. This page explains where _ is allowed and why, shows each use running, and shows the rules the compiler enforces.

Contents

What the underscore means

Java often requires a name for something you never read: the element of a loop that only counts, the exception in a catch that is handled the same way whatever it says, a lambda parameter the interface demands, or the components of a record pattern you do not care about. Naming them ignored or unused works, but a reader has to check that they really are unused, and tools warn about them.

Java 22 gave the single underscore two related meanings:

  • An unnamed variable, as in for (var _ : items) or catch (Exception _). It is declared, its initializer runs and the value is stored, but it has no name, so no code can read it. Several can appear in one scope.
  • An unnamed pattern, as in case Circle(_, double r). It matches any component value, including null, and binds nothing. Circle _ is a type pattern with an unnamed binding: it tests the type without naming the value.

Because an unnamed pattern binds nothing, it also unlocked something new: several patterns in one case, such as case Circle _, Square _ ->. That was impossible before, because a variable bound by only one of the alternatives would be undefined when another matched.

The underscore could be reused this way because it had been retired as a name. Java 8 warned when _ was used as an identifier, and Java 9 made it an error, so no valid Java 9 or later code could contain it.

The underscore through Java versions
VersionStatus of _
Java 1.0 to 7An ordinary identifier, like x
Java 8Still an identifier, with a warning that it will become a keyword
Java 9 to 20A keyword; any use is a compile error
Java 21Unnamed variables and patterns as a preview (JEP 443), with --enable-preview
Java 22 and laterStandard (JEP 456)

All programs on this page were compiled and run on JDK 25 without any preview flags. On JDK 22, 23 or 24 they behave the same.

Unnamed variables

The program shows the five common places for an unnamed variable. Two of the three order IDs start with A and one with B, so the grouping in step 3 produces groups of different sizes.

Java
import java.util.ArrayDeque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class UnnamedVariables {

    static int parseOrZero(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException _) {       // the exception object is not needed
            return 0;
        }
    }

    public static void main(String[] args) {
        // 1. Enhanced for loop that only counts
        List<String> orders = List.of("A-1", "B-7", "A-3");
        int count = 0;
        for (var _ : orders) {
            count++;
        }
        System.out.println("orders counted: " + count);

        // 2. catch parameter
        System.out.println("parse \"42\" -> " + parseOrZero("42") + ", parse \"4x\" -> "
                + parseOrZero("4x"));

        // 3. Lambda parameter required by the signature but not used
        Map<String, Long> perPrefix = orders.stream()
                .collect(Collectors.toMap(o -> o.substring(0, 1), _ -> 1L, Long::sum,
                        TreeMap::new));
        System.out.println("orders per prefix: " + perPrefix);

        // 4. A call made only for its side effect, with several _ in one scope
        Queue<String> queue = new ArrayDeque<>(List.of("header", "skip-me", "data-1", "data-2"));
        var _ = queue.remove();                   // drop the header
        var _ = queue.remove();                   // a second _ is allowed: nothing is declared
        System.out.println("remaining queue: " + queue);

        // 5. Lambda with two parameters where only one matters
        perPrefix.forEach((_, n) -> System.out.println("  a group of size " + n));
    }
}

Output:

Output
orders counted: 3
parse "42" -> 42, parse "4x" -> 0
orders per prefix: {A=2, B=1}
remaining queue: [data-1, data-2]
  a group of size 2
  a group of size 1
  • The loop ran once per order, 3 times, without naming the element.
  • The catch needs only the exception type to decide: "4x" returned 0.
  • toMap requires a value function. Every order counts as 1 whatever its content, so the parameter is _, and the result is {A=2, B=1}.
  • var _ = queue.remove() calls a method for its effect and shows the result is dropped on purpose. Two such declarations sit in one block, which with a real name would be a duplicate variable. The queue lost "header" and "skip-me".
  • In (_, n) -> ... only the value of each map entry is used, and the two group sizes printed.

Unnamed patterns and multiple patterns per case

In a record pattern every component needs a pattern, even when only one matters. The program uses _ on a sealed hierarchy of shapes that each carry a position. The line from (1,5) to (7,5) is horizontal, so its x distance, 6, is its full length.

Java
public class UnnamedPatterns {

    sealed interface Shape permits Circle, Square, Rect, Line {
    }

    record Point(int x, int y) {
    }

    record Circle(Point center, double radius) implements Shape {
    }

    record Square(Point corner, double side) implements Shape {
    }

    record Rect(Point corner, double width, double height) implements Shape {
    }

    record Line(Point from, Point to) implements Shape {
    }

    // _ in a record pattern skips components you do not need
    static double radiusOrSide(Shape s) {
        return switch (s) {
            case Circle(_, double r) -> r;
            case Square(_, double side) -> side;
            case Rect(_, double w, _) -> w;
            case Line(Point(var x1, _), Point(var x2, _)) -> Math.abs(x2 - x1);
        };
    }

    // Several patterns in one case are allowed when none of them binds a variable
    static String dimension(Shape s) {
        return switch (s) {
            case Circle _, Square _, Rect _ -> "2D";
            case Line _ -> "1D";
        };
    }

    public static void main(String[] args) {
        Point o = new Point(0, 0);
        Shape[] shapes = {new Circle(o, 2.5), new Square(o, 3), new Rect(o, 4, 1),
            new Line(new Point(1, 5), new Point(7, 5))};
        for (Shape s : shapes) {
            System.out.printf("%-7s %s  main measure %.1f%n", s.getClass().getSimpleName(),
                    dimension(s), radiusOrSide(s));
        }
    }
}

Output:

Output
Circle  2D  main measure 2.5
Square  2D  main measure 3.0
Rect    2D  main measure 4.0
Line    1D  main measure 6.0
  • Circle(_, double r) skipped the centre and returned the radius 2.5. Rect(_, double w, _) skipped two of three components.
  • Line(Point(var x1, _), Point(var x2, _)) reached into both points, kept the x coordinates and ignored the y coordinates: |7 - 1| = 6.0.
  • case Circle _, Square _, Rect _ -> "2D" handles three record types in one case. In Java 21 this needed three separate cases with the same body, or a default, which would give up the exhaustiveness check.
  • The switch in dimension is still exhaustive without default: the four type patterns cover the sealed interface.

Resources, null components and side effects

Three details matter in real code. The program uses _ for a lock holder in try-with-resources, matches a pin whose position is null, and calls a method with a side effect as the initializer of an unnamed variable.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class UnnamedInPractice {

    // An AutoCloseable used only for its open and close side effects
    record Held(ReentrantLock lock) implements AutoCloseable {
        static Held acquire(ReentrantLock lock) {
            lock.lock();
            System.out.println("  locked, hold count " + lock.getHoldCount());
            return new Held(lock);
        }

        @Override
        public void close() {
            lock.unlock();
            System.out.println("  unlocked, hold count " + lock.getHoldCount());
        }
    }

    record Point(int x, int y) {
    }

    record Pin(Point at, String label) {
    }

    static String describe(Object o) {
        return switch (o) {
            case Pin(Point(var x, _), var label) -> label + " at x=" + x;
            case Pin(_, var label) -> label + " with no position";
            default -> "something else";
        };
    }

    static int nextId(List<String> log) {
        log.add("nextId called");
        return 42;
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        System.out.println("try-with-resources with _:");
        try (var _ = Held.acquire(lock)) {
            System.out.println("  working while locked: " + lock.isHeldByCurrentThread());
        }

        // _ matches null components; a nested record pattern does not
        System.out.println(describe(new Pin(new Point(3, 4), "home")));
        System.out.println(describe(new Pin(null, "draft")));

        // The initializer of an unnamed variable is still evaluated
        List<String> log = new ArrayList<>();
        var _ = nextId(log);
        System.out.println("side effects kept: " + log);
    }
}

Output:

Output
try-with-resources with _:
  locked, hold count 1
  working while locked: true
  unlocked, hold count 0
home at x=3
draft with no position
side effects kept: [nextId called]
  • The lock was held inside the block and released at the end: hold count 1, then 0. The resource exists only for its close(). With a named variable, javac -Xlint:try warns "auto-closeable resource r is never referenced in body"; with _ there is no warning, because not referencing it is the declared intent.
  • The pin "draft" has a null position. It did not match Pin(Point(var x, _), var label), because a nested record pattern never matches null. It did match Pin(_, var label), because the unnamed pattern matches anything, null included.
  • var _ = nextId(log) still called nextId, and the log shows it. An unnamed variable drops the name, not the evaluation.

Trap: an unnamed catch that hides bugs

catch (Exception _) is short and looks tidy, which makes it tempting to write too broadly. The program reads integer settings from a map: "port" is valid, "timeout" holds 30s, which is not a number, and "prot" is a typo for a key that does not exist.

Java
import java.util.Map;

public class CatchTrap {

    static final Map<String, String> SETTINGS = Map.of("port", "8080", "timeout", "30s");

    // Too broad: catch (Exception _) also hides the bug of asking for a missing key
    static int broad(String key) {
        try {
            return Integer.parseInt(SETTINGS.get(key).strip());
        } catch (Exception _) {
            return -1;
        }
    }

    // Narrow: only the expected failure is ignored, everything else still surfaces
    static int narrow(String key) {
        try {
            return Integer.parseInt(SETTINGS.get(key).strip());
        } catch (NumberFormatException _) {
            return -1;
        }
    }

    public static void main(String[] args) {
        for (String key : new String[] {"port", "timeout", "prot"}) {
            String result;
            try {
                result = String.valueOf(narrow(key));
            } catch (NullPointerException e) {
                result = "NullPointerException (the key is missing)";
            }
            System.out.printf("%-8s broad=%-3d narrow=%s%n", key, broad(key), result);
        }
    }
}

Output:

Output
port     broad=8080 narrow=8080
timeout  broad=-1  narrow=-1
prot     broad=-1  narrow=NullPointerException (the key is missing)
  • Both versions read 8080 for "port" and returned -1 for "timeout", the case the code was written to handle.
  • For the misspelled "prot", SETTINGS.get returned null and strip() threw NullPointerException. The broad version swallowed it and returned -1, exactly as if the value had been malformed, so the typo would go unnoticed in production. The narrow version let the exception through.
  • Use _ only for the exception type you have decided to ignore, and keep a name, and a log statement, for anything else. A multi-catch such as catch (NumberFormatException | DateTimeParseException _) is allowed when several expected types need the same handling.

What the compiler allows and rejects

The program compiles eight small classes in memory with the javax.tools compiler, some with --release 8 and --release 9 to show the history, and prints each warning and error.

Java
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

// Compiles small classes in memory and prints javac's verdict on each use of _
public class UnderscoreRules {

    public static void main(String[] args) {
        check("8", "_ as an ordinary name, Java 8", "void m() { int _ = 1; int y = _ + 1; }");
        check("9", "_ as an ordinary name, Java 9", "void m() { int _ = 1; }");
        check("25", "reading an unnamed variable", "void m() { int _ = 1; int y = _ + 1; }");
        check("25", "unnamed field", "int _ = 1;");
        check("25", "unnamed method parameter", "void m(int _) { }");
        check("25", "two bindings in one case", "record A(int x) {} record B(int x) {}"
                + " int m(Object o) { return switch (o) { case A(int x), B(int x) -> x;"
                + " default -> 0; }; }");
        check("25", "_ as a whole case label", "int m(Object o) {"
                + " return switch (o) { case _ -> 0; }; }");
        check("25", "unused lambda parameters", "java.util.function.BiFunction<String,"
                + " Integer, Integer> f = (_, _) -> 0;");
    }

    static void check(String release, String label, String members) {
        String source = "class T { " + members + " }";
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
        JavaFileObject file = new SimpleJavaFileObject(
                URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return source;
            }
        };
        List<String> options = List.of("--release", release, "-Xlint:-options", "-d",
                System.getProperty("java.io.tmpdir"));
        boolean ok = javac.getTask(null, null, diags, options, null, List.of(file)).call();
        System.out.println(label + ": " + (ok ? "compiles" : ""));
        for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
            String text = d.getMessage(Locale.ENGLISH).strip();
            System.out.println("  " + d.getKind().toString().toLowerCase(Locale.ROOT) + ": "
                    + String.join(" ", text.split("\\s*\\n\\s*")));
        }
    }
}

Output:

Output
_ as an ordinary name, Java 8: compiles
  warning: as of release 9, '_' is a keyword, and may not be used as an identifier
  warning: as of release 9, '_' is a keyword, and may not be used as an identifier
_ as an ordinary name, Java 9: 
  error: unnamed variables are not supported in -source 9 (use -source 22 or higher to enable unnamed variables)
reading an unnamed variable: 
  error: underscore not allowed here
unnamed field: 
  error: underscore not allowed here
unnamed method parameter: 
  error: underscore not allowed here
two bindings in one case: 
  error: illegal attempt to redefine an existing match binding
_ as a whole case label: 
  error: underscore not allowed here
unused lambda parameters: compiles
  • With --release 8, _ worked as an ordinary name, read and all, with two warnings that it would become a keyword. With --release 9 it is an error; the current compiler's message points to Java 22 for the new meaning.
  • An unnamed variable can never be read: _ + 1 is "underscore not allowed here".
  • Fields and method parameters cannot be unnamed. They are part of a class's API, where a name documents the meaning even if this implementation ignores the value.
  • Two record patterns that both bind x cannot share a case, even with the same name and type: "illegal attempt to redefine an existing match binding". Only unnamed bindings can be combined.
  • case _ on its own is not allowed; use default. The unnamed pattern exists only inside record patterns.
  • A lambda may have several _ parameters, as in (_, _) -> 0.

Where _ can appear

Places where _ is allowed (Java 22 and later)
PlaceExampleTypical reason
Local variablevar _ = queue.remove();Call made only for its side effect
Enhanced for loopfor (var _ : items)Counting or repeating
Basic for loopfor (int i = 0, _ = sideEffect(); i < n; i++)Rare: an initializer run once
catch parametercatch (NumberFormatException _)Type is enough to decide
Lambda parameter(_, value) -> ...Signature demands a parameter
try-with-resourcestry (var _ = lock.acquire())Resource used only for open and close
Record pattern componentCircle(_, double r)Component not needed
Type patterncase Line _ ->Type matters, value does not

When to use it, and when not

Choosing between _ and a name
SituationUse
The value is truly irrelevant_
The exception should be logged or wrappedA name: swallowing it with _ hides failures
Several record types share one branchcase A _, B _ ->
Most components of a large record are ignoredA type pattern plus accessors may read better than many _
Code must compile on Java 21 or olderA descriptive name such as ignored
A method parameter you do not useA name; _ is not allowed there

The underscore builds on record patterns and pattern matching for switch; see those pages for how the surrounding patterns work.