Javatpoint Logo
Javatpoint Logo

Java instanceof operator

The java 'instanceof' operator is used to test whether an object is an instance of a specified type (class or sub - class or visual interface).

'instanceof' in Java is also known as the type comparison operator because it compares the instances with type. It returns true or false. If we apply the 'instanceof' operator with a variable value, the value returned is false.

Example of Java instanceof Operator

Let's look at a simple example of instanceof operator where it checks the current class.

student.java

Output:

true

An object of subclass type is also a type of parent class. For example, if a 'student' class extends the 'Teacher' class, then object of student class can be referred by either the student class itself or Teacher class. Let us consider the following example to understand this point more clearly.

Let's see another example.

Student.java

Output:

true

Using instanceof Operator with a Variable that has Null Value

Let's take some time here to think of the outcome if the instanceof operator is used with a variable that has null value. The answer is that it returns false. Consider the following example to gain better understanding of this point.

Student.java

Output:

false

Downcasting with Java instanceof Operator

In Downcasting the object of the parent class is assigned to the base class. On performing it directly, the compiler gives Compilation error. On the other hand, if we try to perform it by typecasting, ClassCastException is thrown at runtime. Downcasting is easily possible using 'instanceof' operator.

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

Compiles successfully but ClassCastException is thrown at runtime

Possibility of downcasting with instanceof Operator

Let's see the example, where downcasting is possible by instanceof operator.

Student.java

Output:

Cool! Downcasting successfully performed!

Downcasting without the use of Java instanceof Operator

Let's see how we can perform downcasting without using the instanceof operator as shown in the following example:

Student.java

Output:

Cool! Downcasting successfully performed!

Understanding Real use of instanceof in java

Consider the example given below to understand what we have covered so far.

Temp1.java

Output:

This is the method of Teacher class

Next TopicJava Localization





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA