Instanceof patterns
What you will learn
An instanceof type pattern combines a runtime type test with a variable declaration. When the test succeeds, Java initializes the new variable with the matched object. Record patterns can additionally unpack components, removing repetitive accessor calls. Both make code that handles different input shapes easier to read without unchecked casts.
- Use type patterns and flow-scoped variables with if, && and early returns.
- Use nested record patterns and distinguish a failed match from an exception.
Use a fresh folder for each complete Main.java example. Compile with javac --release 21 Main.java and run java Main. Requires JDK 21 or a compatible newer JDK. The examples use the standard library only.
Read a label only when the input is text
public class Main { static int textLength(Object value) { if (value instanceof String text && !text.isBlank()) { return text.length(); } return 0; } public static void main(String[] args) { System.out.println(textLength("Map")); System.out.println(textLength(" ")); System.out.println(textLength(42)); System.out.println(textLength(null)); }}Expected output:
3000The right operand of && runs only when the left operand succeeded. Therefore text is in scope and initialized when isBlank runs. Non-strings and null fail the pattern and produce zero. length measures UTF-16 code units, not displayed characters.
Rules and mental model
Type patterns for instanceof became permanent in Java 16; record patterns became permanent in Java 21. A type pattern has the form Type variable. A record pattern has the form RecordType(componentPattern, ...), with one pattern per component in declared order. Component values are obtained using the record accessors; a nested record pattern can recursively unpack another record. An accessor that throws during matching causes MatchException, not a simple false result. A top-level null never matches an instanceof pattern. Within a record pattern, a type pattern unconditional for the declared component type can bind a null component, but a nested record pattern cannot unpack null. Use explicit domain validation or guards when null is invalid. The compiler checks type compatibility and scope: a variable is available only where matching is guaranteed. Pattern matching neither clones objects nor validates their contents automatically.
Use an early return to reject the wrong type
public class Main { record Badge(String name, int level) {} static String describe(Object value) { if (!(value instanceof Badge badge)) return "not a badge"; return badge.name() + ":" + badge.level(); } public static void main(String[] args) { System.out.println(describe(new Badge("Reader", 2))); System.out.println(describe("Reader")); System.out.println(describe(null)); }}Expected output:
Reader:2not a badgenot a badgeAfter the guard, every reachable path has matched Badge. The variable badge can therefore be used after the if statement. A pattern variable is scoped according to control flow, not simply the braces around its textual declaration.
Unpack a nested record
public class Main { record Location(String aisle, int shelf) {} record Parcel(Location location, int units) {} static String locate(Object value) { if (value instanceof Parcel(Location(String aisle, int shelf), int units)) { return aisle + shelf + ":" + units; } return "unavailable"; } public static void main(String[] args) { System.out.println(locate(new Parcel(new Location("B", 4), 2))); System.out.println(locate(new Parcel(null, 2))); System.out.println(locate(new Parcel(new Location(null, 4), 2))); }}Expected output:
B4:2unavailablenull4:2The nested Location record pattern fails for a null location. A String type pattern for a String-typed record component is unconditional for that component type and can bind null inside the record pattern; concatenation then prints null. Validate domain data separately if a non-null aisle is required.
Common mistakes
Do not use value instanceof String text || text.isBlank(); if the left side is false, text does not exist on the right. Use && for a condition that requires a successful match. Do not expect a pattern to validate a record field or replace all exception handling. Match only shapes you actually need; normal interface methods remain better for behavior owned by the object.
Practice
Create record Dimensions(int width, int height) and record Poster(Dimensions size, String title). Implement describe(Object) using a nested record pattern and a guard that accepts only positive dimensions and non-null titles. Return title followed by width x height (no spaces around x), or invalid. Test valid data, null size, zero width and null title.
Check your result with the chapter practice task and explain why it works.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Instanceof patterns — knowledge check
Apply sealing, flow scope and pattern switch rules using Java 21-compatible examples.
What is textLength(null)?
Why is text usable after &&?
Why is badge usable after the negated guard with return?
What does locate(new Parcel(null, 2)) return?
What if a record accessor throws during matching?