What is the 'instanceof' operator used for in Java?

instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.

Imagine:

interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}

Imagine a dog object, created with Object dog = new Dog(), then:

dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal   // true - Dog extends Animal
dog instanceof Dog      // true - Dog is Dog
dog instanceof Object   // true - Object is the parent type of all objects

However, with Object animal = new Animal();,

animal instanceof Dog // false

because Animal is a supertype of Dog and possibly less "refined".

And,

dog instanceof Cat // does not even compile!

This is because Dog is neither a subtype nor a supertype of Cat, and it also does not implement it.

Note that the variable used for dog above is of type Object. This is to show instanceof is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.

Things to note: expressionThatIsNull instanceof T is false for all Types T.


It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}

As described on this site:

The instanceof operator can be used to test if an object is of a specific type...

if (objectReference instanceof type)

A quick example:

String s = "Hello World!"
return s instanceof String;
//result --> true

However, applying instanceof on a null reference variable/expression returns false.

String s = null;
return s instanceof String;
//result --> false

Since a subclass is a 'type' of its superclass, you can use the instanceof to verify this...

class Parent {
    public Parent() {}
}

class Child extends Parent {
    public Child() {
        super();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println( child instanceof Parent );
    }
}
//result --> true

I hope this helps!