instanceof operator in Java

The instanceof operator in Java is an operator used to check if this object is an instance of a certain class or interface or not? The return result of this operator will be true if the object is an instance of the class you are checking, otherwise false.

For example, I have an Application class as follows:

In the main() method of this class, I initialize an object of class Application and use the instanceof operator to check if this object is an instance of this Application class or not? You will see the following results:

instanceof operator in Java

If you write the following code:

then IDE will have an error:

instanceof operator in Java

This is in the case of too obvious, the IDE can report the error to you immediately, but if you have an interface with two implementations as follows:

then now if you initialize the object of Triangle class but check if this object is an instance of class Rectangle:

The IDE will not be able to detect errors at compile time, but when running, you will see the following results:

instanceof operator in Java

We will often use the instanceof operator in case of checking whether a method’s parameter is an instance of a certain class. Eg:

In the above method, the interface Shape parameter has many different implementations, in the body of the method, we will check if the instance passed to this method is Triangle or not? If it is correct, then continue to process.

Result:

instanceof operator in Java

From Java 14, you can rewrite the check() method using pattern matching instanceof, as simple as:

With the new way, we don’t need to write a single line of code to cast the instance of the object we want. All will be done in the if block, the result remains the same:

instanceof operator in Java

Add Comment