Skip to lesson

instanceof and pattern matching

A method receives an Animal, but you need Dog-only behaviour. A wrong cast crashes the program, so how do you check first?

Check before you cast

The instanceof operator tests whether an object IS-A given type and gives true or false, as in a instanceof Dog. It is true for the object's own class and every parent above it, and always false for null.

A downcast on the wrong object throws ClassCastException. So test first: if (a instanceof Dog) { Dog d = (Dog) a; d.fetch(); }. The cast then runs only when it is sure to work.

Example 1 · What instanceof says

InstanceofDemo.javaJava
class Animal { }
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs");    }}
public class InstanceofDemo {    public static void main(String[] args) {        Animal a = new Dog();        System.out.println(a instanceof Dog);        System.out.println(a instanceof Animal);        System.out.println(a instanceof Object);        System.out.println(a instanceof Cat);    }}
Output
true
true
true
false

What this code does

  • The object is a Dog, so it is also an Animal and an Object: three trues.
  • a instanceof Cat compiles (an Animal could be a cat) but is false for this object.

Example 2 · Check, then cast, in a loop

SafeCastDemo.javaJava
class Animal { }
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs");    }}
public class SafeCastDemo {    public static void main(String[] args) {        Animal[] pets = { new Dog(), new Cat(), new Dog() };        for (Animal a : pets) {            if (a instanceof Dog) {                Dog d = (Dog) a;                d.fetch();            } else if (a instanceof Cat) {                Cat c = (Cat) a;                c.climb();            }        }    }}
Output
Dog fetches
Cat climbs
Dog fetches

What this code does

  • Each cast runs only after instanceof has said true, so no ClassCastException is possible.
  • This is the classic pre-Java-16 style: one line to test, one line to cast.

instanceof looks at the object, not the variable. A puppy object also passes instanceof Dog, which matches the casting rule from Downcasting (opens in a new tab): a cast to Dog works for a puppy too.

null, and checks that cannot compile

null is not an instance of anything, so x instanceof Dog is simply false when x is null. It never throws a NullPointerException, so no separate x != null check is needed.

Example 3 · null is never an instance

NullCheckDemo.javaJava
class Animal { }
class Dog extends Animal {    void fetch() {        System.out.println("Dog fetches");    }}
class Cat extends Animal {    void climb() {        System.out.println("Cat climbs");    }}
public class NullCheckDemo {    static void describe(Animal a) {        if (a instanceof Dog) {            System.out.println("A dog");        } else if (a instanceof Cat) {            System.out.println("A cat");        } else {            System.out.println("Not a dog or a cat: " + a);        }    }
    public static void main(String[] args) {        describe(new Cat());        describe(null);    }}
Output
A cat
Not a dog or a cat: null

What this code does

  • null instanceof Dog is simply false: no exception, no extra null check needed.
  • So describe(null) falls into the else branch and prints null.

Like a cast, a check that can never be true does not compile. If c is a Cat variable, c instanceof Dog gives incompatible types: Cat cannot be converted to Dog.

Pattern matching: test and cast in one step

Pattern matching for instanceof is a type test that also declares a variable, as in if (a instanceof Dog d). When the test is true, Java casts the object and stores it in the pattern variable d, so no separate cast is written. It needs Java 16 or newer.

Writing a test and then a cast repeats the type twice, and a copy-paste slip can cast to the wrong type. A pattern names the variable right after the type.

Example 4 · Pattern matching with &&

PatternDemo.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
class Topper extends Student {    int rank;
    Topper(String name, int marks, int rank) {        super(name, marks);        this.rank = rank;    }}
public class PatternDemo {    public static void main(String[] args) {        Student[] list = { new Student("Rohan", 74), new Topper("Kavya", 98, 1), new Topper("Arjun", 93, 3) };        for (Student s : list) {            if (s instanceof Topper t && t.rank == 1) {                System.out.println(t.name + ": rank 1, full scholarship");            } else if (s instanceof Topper t) {                System.out.println(t.name + ": rank " + t.rank);            } else {                System.out.println(s.name + ": " + s.marks + " marks");            }        }    }}
Output
Rohan: 74 marks
Kavya: rank 1, full scholarship
Arjun: rank 3

What this code does

  • s instanceof Topper t tests and casts in one step; t is a Topper reference, so t.rank compiles.
  • After &&, t already exists, because the right side runs only when the test was true.

The pattern variable exists only where the test is surely true: inside the if block, or after && in the same condition. With the flipped form, if (!(o instanceof Book b)) return false;, b can be used for the rest of the method.

Find the bug

Find the instanceof bug

Select the line that is wrong.

Only dogs should fetch. A Cat object is in a.

Round 1 of 4

instanceof inside equals()

In The equals() method (opens in a new tab), equals() checked getClass() and then cast. A pattern does the null check, the type check and the cast in one line.

Example 5 · equals() with an instanceof pattern

BookEqualsDemo.javaJava
final class Book {    private final String isbn;    private final String title;
    Book(String isbn, String title) {        this.isbn = isbn;        this.title = title;    }
    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (!(o instanceof Book other)) {            return false;        }        return isbn.equals(other.isbn);    }
    @Override    public int hashCode() {        return isbn.hashCode();    }}
public class BookEqualsDemo {    public static void main(String[] args) {        Book b1 = new Book("978-81", "Wings of Fire");        Book b2 = new Book("978-81", "Wings of Fire (paperback)");        System.out.println(b1.equals(b2));        System.out.println(b1.equals(null));        System.out.println(b1.equals("978-81"));    }}
Output
true
false
false

What this code does

  • One line handles null, a wrong type and the cast: after it, other is a Book reference.
  • Book is final, so no child class exists, and instanceof behaves exactly like the getClass() check.

One difference: instanceof is true for child objects too, while getClass() demands the exact same class. For a final class both behave the same. For a class with children, getClass() keeps equals() symmetric.

When instanceof is a design smell

A chain like if (s instanceof Circle) ... else if (s instanceof Square) ... needs a new branch for every new shape. Overriding moves each rule into its own class.

Example 6 · Replacing an instanceof chain with overriding

NoChainDemo.javaJava
class Shape {    double area() {        return 0;    }}
class Circle extends Shape {    double r;
    Circle(double r) {        this.r = r;    }
    @Override    double area() {        return 3.14 * r * r;    }}
class Square extends Shape {    double side;
    Square(double side) {        this.side = side;    }
    @Override    double area() {        return side * side;    }}
public class NoChainDemo {    static double areaWithChain(Shape s) {        if (s instanceof Circle c) {            return 3.14 * c.r * c.r;        } else if (s instanceof Square sq) {            return sq.side * sq.side;        }        return 0;    }
    public static void main(String[] args) {        Shape[] shapes = { new Circle(10), new Square(4) };        for (Shape s : shapes) {            System.out.println(areaWithChain(s) + " = " + s.area());        }    }}
Output
314.0 = 314.0
16.0 = 16.0

What this code does

  • areaWithChain needs a new branch for every new shape; s.area() needs nothing, because each object knows its own area.
  • Both give the same numbers, but the overriding version is the one to keep.

Use instanceof for real "maybe" cases: equals(), or an optional extra that only some objects have, such as cashback on UPI payments. When every type has its own version of a rule, override a method instead.

Next step

Check your understanding

12 quick questions