Course contentsShow
← Java
Lesson 453 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

Pattern Matching for instanceof: Basic Syntax

Introduce Java 16's pattern matching syntax that combines type test and variable binding in one expression.

Pattern Matching for instanceof: Basic Syntax

What you'll learn: How Java 16+ lets you combine type checking and casting into one clean line of code.

The Old Boilerplate Problem

Remember the test-cast-use pattern you just learned? You'd check the type with instanceof, then manually cast, then use the variable:

if (animal instanceof Dog) {
    Dog dog = (Dog) animal;  // Explicit cast
    dog.bark();
}

That explicit cast on line 2 felt redundant—Java already knew it was a Dog from the instanceof check on line 1!

Pattern Matching to the Rescue

Java 16 introduced pattern matching for instanceof, which combines the type test and variable binding in one expression:

if (animal instanceof Dog dog) {
    dog.bark();  // 'dog' is already cast and ready to use!
}

Notice the syntax: instanceof Dog dog. You declare a pattern variable (dog) right in the instanceof expression. If the check passes, Java automatically casts animal to Dog and binds it to the variable dog.

How It Works

Think of it like a two-in-one operation:

  • Test: "Is this object a Dog?"
  • Bind: "If yes, give me a Dog-typed variable I can use immediately."

The pattern variable dog is only in scope where the compiler knows the instanceof test passed—inside the if block.

Simple Example

Object obj = "Hello";

if (obj instanceof String text) {
    System.out.println(text.toUpperCase());  // HELLO
}

No explicit cast needed—text is automatically a String reference.

Key Takeaway:
Pattern matching for instanceof eliminates boilerplate by combining the type check and cast into a single expression, automatically creating a properly-typed variable you can use immediately.