Java instanceof Operator

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.

Its syntax is

objectName instanceOf className;

Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns false.


Example: Java instanceof

Output

name is an instance of String: true
obj is an instance of Main: true

In the above example, we have created a variable name of the String type and an object obj of the Main class.

Here, we have used the instanceof operator to check whether name and obj are instances of the String and Main class respectively. And, the operator returns true in both cases.

Note: In Java, String is a class rather than a primitive data type. To learn more, visit Java String.


Java instanceof during Inheritance

We can use the instanceof operator to check if objects of the subclass is also an instance of the superclass. For example,

In the above example, we have created a subclass Dog that inherits from the superclass Animal. We have created an object d1 of the Dog class.

Inside the print statement, notice the expression,

d1 instanceof Animal

Here, we are using the instanceof operator to check whether d1 is also an instance of the superclass Animal.


Java instanceof in Interface

The instanceof operator is also used to check whether an object of a class is also an instance of the interface implemented by the class. For example,

In the above example, the Dog class implements the Animal interface. Inside the print statement, notice the expression,

d1 instanceof Animal

Here, d1 is an instance of Dog class. The instanceof operator checks if d1 is also an instance of the interface Animal.

Note: In Java, all the classes are inherited from the Object class. So, instances of all the classes are also an instance of the Object class.

In the previous example, if we check,

d1 instanceof Object

The result will be true.