instanceof Operator in Java

instanceof operator in Java is used to test the type of an object during run time.

The syntax of instanceof operator in Java is as follows-

Here objRef is a reference to an instance.
objType denotes a class type.

Using instanceof operator you can check if objRef is of the type objType or not. If yes the instanceof operator returns true otherwise false.

Using instanceof operator in Java

instanceof operator can help in preventing ClassCastException at run time.

For example a parent class reference can refer to child class but the opposite, child class referring to parent class, results in compile time error without type casting.

This down casting (parent to child) will result in ClassCastException if there are more than one children and you are trying to cast with out knowing the actual type. This scenario is shown in the following Java example where we have two child classes Child and AnotherChild. In the method methodToCast you are trying to cast to Child even when the AnotherChild reference is passed resulting in ClassCastException.

Output

In such scenario you need to use instanceof operator to check the type of the reference.

Consider another scenario where you have multi-level inheritance.

Output

As you can see casting works for Child and GrandChild (as it is also of type Child) but throws ClassCastException for AnotherChild which is of type Parent. In this scenario again check for the type using the instanceof operator ensures that the method is called only for Child types references.

Points about instanceof operator in Java

1- If object reference is null instanceof operator returns false.

Output

2- Testing with instanceof operator with Object class always returns true as Object class is super class of all the classes in Java.

Output

That’s all for the topic instanceof Operator in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.