Introduction To Instanceof Operator In Java

Introduction

 
This article describes the instanceof operator in Java.
 

Description

 
The instanceof operator allows you to determine the type of an object. The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It takes an object on the left side of the operator and a type on the right side of the operator and returns a Boolean value indicating whether the object belongs to that type or not.
 
It is also known as a type comparison operator since it compares the instance types. They return a Boolean value (in other words either true or false). If we apply the instanceof operator with any variable that has a null value then it returns false.
 
1. Example
 
In this example, a class "A" is created to show the instance reference.
  1. class A {  
  2.  public static void main(String args[]) {  
  3.   A a = new A();  
  4.   System.out.println(a instanceof A);  
  5.  }  
  6. }  
Output
 
fig-1.jpg
 
2. Example
 
An object of subclass type is also a type of parent class.
 
For example, if the Apple class extends the Fruit then the Apple object can be referred to by either the Apple or Fruit class.
  1. class Fruit {}  
  2. class Apple extends Fruit {  
  3.  public static void main(String args[]) {  
  4.   Apple app = new Apple();  
  5.   System.out.println(app instanceof Fruit);  
  6.  }  
  7. }   
Output
 
fig-2.jpg
 
3. Example
 
Instanceof compares the type of Operator. The instanceof operator compares an object with the specified type.

The following program, InstanceofEx, defines a parent class (named Main), a simple interface (named MyInterface), and a child class (named Derived) that inherits from the Main and implements the interface.
  1. class InstanceofEx {  
  2.  public static void main(String args[]) {  
  3.   Main m1 = new Main();  
  4.   Main m2 = new Derived();  
  5.   System.out.println("m1 instanceof Main: " + (m1 instanceof Main));  
  6.   System.out.println("m1 instanceof Derived: " + (m1 instanceof Derived));  
  7.   System.out.println("m1 instanceof MyInterface: " + (m1 instanceof MyInterface));  
  8.   System.out.println("m2 instanceof Main: " + (m2 instanceof Main));  
  9.   System.out.println("m2 instanceof Derived: " + (m2 instanceof Derived));  
  10.   System.out.println("m2 instanceof MyInterface: " + (m2 instanceof MyInterface));  
  11.  }  
  12. }   
class Main {}
class Derived extends Main implements MyInterface {}
interface MyInterface {}
 
Output:
 
fig-3.jpg

Note: When we use the instanceof operator, always remember that null is not an instance of anything.