Java instanceof | Comparison Operator with How to use example

The Java instanceof operator used to check the object is an instance of the specified type (class or subclass or interface). When you using the Instnaceof operator for comparison then it will return a boolean value either Ture or False.

Java instanceof Comparison Operator with How to use example

Java instanceof Operator also known as a Comparison Operator. Because it compares the instance with types.

Syntax:

Instanceof operator is used only for object reference variables. The syntax of written as −

Java instanceof example

A Simple example, were creating an Instance (object) of class then checking it with class. See the below code and example.

Output: true

Another example 

Let do this time Inheritance and check whether a subclass Instance of superclass or not.

Output: Is bike instance of Vehicle – true

One More example 

This time we check the parent object is not an instance of Child. For that, we using the above same example and only change creating an object of Parent class.

Output: Parent Object is NOT instance of Child
false

Comparison Operator

The standard comparison operators work for primitive values like int, double, char, etc. And the == and != operators can be used to compare object references. To see a comparison between an object (instance), can use an instanceof Comparison Operator.

Question: What is the difference between instanceof operator vs isInstance() method in Java?

Answer: A both instanceof operator and isInstance() method is used for testing a wheater instance(object) belongs to the specified type or not.

But there is a difference comes when you want to check the class of object dynamically. In this case, isInstance() method will work. Otherside with instanceof operator no way to do this.

One more similarity both have returned a Boolean value- Ture or False.

Question: What is the Java instanceof performance?

Answer: In many cases there are better OOP ways to achieve the desired behavior. It depends on the code and the JVM version.

Do comment if you have any suggestions and doubts on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java instanceof class Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

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