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

Ben picture Ben · Sep 6, 2011 · Viewed 241.8k times · Source

What is the instanceof operator used for? I've seen stuff like

if (source instanceof Button) {
    //...
} else {
    //...
}

But none of it made sense to me. I've done my research, but came up only with examples without any explanations.

Answer

user166390 picture user166390 · Sep 6, 2011

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.

Happy coding.