J.VII · Java 25 practice question

Consider the following scenario using Java 25's pattern matching features, focusing on record pattern nesting within a switch expression. Given this structure, which switch case pattern correctly captures a `NestedRecord` whose `inner` field is an `InnerRecord` instance?

record InnerRecord(String value) {}
record NestedRecord(InnerRecord inner) {}

public String analyze(Object input) {
    return switch (input) {
        // choose the correct case pattern here
        default -> "No match";
    };
}
Choose one answer
Check answer and explanation

Correct answer: `case NestedRecord(InnerRecord inner) -> ...`

Explanation

In Java 25 (and patterns matching in general), when you want to destructure a record pattern and ensure the field matches a specific type *without* requiring further deep deconstruction within the match guard, you use the standard field pattern. Option A correctly destructures `NestedRecord` into `inner` and confirms `inner` is of type `InnerRecord`. Option B attempts to destructure the inner record immediately, which is more complex than what the prompt asks for regarding capturing the structure.

Common trap

The trap lies in confusing the structure matching (destructuring the outer record) with deep destructuring (matching the inner record's fields simultaneously). The syntax for matching an outer record whose field is a specific type is straightforward field pattern matching.

Source: Pattern Matching Documentation (Check specific JEP details for Java 25) https://docs.oracle.com/en/java/javase/25/language/pattern-matching.html
Checked against the cited text on 2026-11-27.

Report an error in this question