Unnamed patterns and variables (preview)

Java 21 Course · lesson 11 of 15 · 3 min read

The underscore says "something is here and I do not care", which removes a lot of noise.

Open this lesson in the learning hub

Key points

  • In a record pattern you often need a component to match but never read it.
  • Naming it forces a meaningless identifier and an unused-variable warning.
  • _ matches and discards: case Point(int x, _).
  • It also works for unused catch parameters and loop variables.
  • Preview in 21, finalised in Java 22 - so on 22+ you can use it without a flag.

Example

// Preview in Java 21 (finalised in 22) - needs --enable-preview on 21.
public class Main {
    record Point(int x, int y) { }
    record Line(Point from, Point to) { }

    static int leftEdge(Line l) {
        // We only care about the starting x
        return switch (l) {
            case Line(Point(int x, _), _) -> x;
        };
    }

    public static void main(String[] args) {
        System.out.println(leftEdge(new Line(new Point(4, 9), new Point(20, 3))));

        try {
            Integer.parseInt("nope");
        } catch (NumberFormatException _) {          // unnamed catch parameter
            System.out.println("could not parse, and I do not need the exception object");
        }
    }
}

The underscore documents "matched but deliberately ignored" instead of inventing a name nobody reads.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 21 Course course, and every lesson in it is listed on the Java 21 Course contents page.