instanceof operator in Java

Rumman Ansari   Software Engineer   2022-03-03   10352 Share
☰ Table of Contents

Table of Content:


Note: If you are beginner to java, skip this topic and return to it after class, object, inheritance, polymorphism concepts.

In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.

with a simple words The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.


The instanceof operator has this general form:
 objref instanceof type
 

Here, objref is a reference to an instance of a class, and type is a class type. If objref is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.

instanceof is a Java keyword. Every letter in a Java keyword is in lowercase.

Example of instanceOf

Program:

Let's see the simple example of instanceof operator where it tests the current class.

 public class TestInstance
{
    public static void main(String[] args)
    {
      TestInstance t= new TestInstance();
      System.out.println(t instanceof TestInstance);
      }
}
 

Output:

 true
Press any key to continue . . .
 

Another example of java instanceof operator

Program:

Let's see the simple example of instanceof operator where it tests the current class.

class Human{

	}

class Woman extends Human{//Woman inherits Animal

 public static void main(String args[]){
 Woman d=new Woman();
 System.out.println(d instanceof Human);//true
 }
}
 

Output:

 true
Press any key to continue . . .
 

An object of subclass type is also a type of parent class. In this example, if Woman extends Human then object of Woman can be referred by either Woman or Human class.

instanceof in java with a variable that have null value

If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example given below where we apply instanceof operator with the variable that have null value.

Program:

class Woman{
 public static void main(String args[]){
  Woman p=null;
  System.out.println(p instanceof Woman);//false
 }
}
 

Output:

false
Press any key to continue . . .
 

Casting Objects and the instanceof Operator

One object reference can be typecast into another object reference. This is called casting object.

When Child class type refers to the object of Parent class, it is known as downcasting. If we perform it directly, compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime. But if we use instanceof operator, downcasting is possible.

casting objects instanceof1
 Child c = new Parent();//Compilation error 
 

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

 Child d=(Child)new Parent();  
//Compiles successfully but ClassCastException is thrown at runtime
 
casting objects instanceof1

Solution downcasting with instanceof

Program:

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

class Parent { }

class Child extends Parent {
  static void method(Parent a) {
    if(a instanceof Child){
       Child d=(Child)a;//downcasting
       System.out.println("solve downcasting performed");
    }
  }

  public static void main (String [] args) {
    Parent a=new Child();
    Child.method(a);
  }

 }
 

Output:

solve downcasting performed
Press any key to continue . . .
 

Downcasting without the use of java instanceof

Downcasting can also be performed without the use of instanceof operator as displayed in the following example:

Program:

class Parent {

	}
class Child extends Parent {
  static void method(Parent a) {
       Child d=(Child)a;//downcasting
       System.out.println("downcasting performed");
  }
   public static void main (String [] args) {
    Parent a=new Child();
    Child.method(a);
  }
}
 

Output:

downcasting performed
Press any key to continue . . .
 

Let's take closer look at this, actual object that is referred by a, is an object of Child class. So if we downcast it, it is fine. But what will happen if we write:

 Parent a=new parent();  
Child.method(a);  
//Now ClassCastException but not in case of instanceof operator  
 

Example of downcasting with instanceof operator

Program:

class Parent{ }

public class Child extends Parent
{
    public void check()
    {
        System.out.println("Sucessfull Casting");
    }

    public static void show(Parent p)
    {
       if(p instanceof Child)
       {
           Child b1=(Child)p;
           b1.check();
       }
    }

    public static void main(String[] args)
    {

      Parent p=new Child();

      Child.show(p);

      }
}
 

Output:

Sucessfull Casting
Press any key to continue . . .
 

Another example of instanceof operator

Program:

class Parent{}

class Child1 extends Parent{}

class Child2 extends Parent{}

class MainClass
{
  public static void main(String[] args)
  {
      Parent p =new Parent();
      Child1 c1 = new Child1();
      Child2 c2 = new Child2();

      System.out.println(c1 instanceof Parent);		//true
      System.out.println(c2 instanceof Parent);		//true
      System.out.println(p instanceof Child1);		//false
      System.out.println(p instanceof Child2);		//false

      p = c1;
      System.out.println(p instanceof Child1);		//true
      System.out.println(p instanceof Child2);		//false

      p = c2;
      System.out.println(p instanceof Child1);		//false
      System.out.println(p instanceof Child2);		//true

   }

}
 

Output:

true
true
false
false
true
false
false
true
Press any key to continue . . .
 

Important example of instanceof operator

Program:

// Demonstrate instanceof operator.
class A {
	int i, j;
}

class B {
	int i, j;
}

class C extends A {
	int k;
}

class D extends A {
	int k;
}

class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
	System.out.println("a is instance of A");

if(b instanceof B)
	System.out.println("b is instance of B");

if(c instanceof C)
	System.out.println("c is instance of C");

if(c instanceof A)
	System.out.println("c can be cast to A");

if(a instanceof C)
	System.out.println("a can be cast to C");
	System.out.println();
// compare types of derived types
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if(ob instanceof D)
	System.out.println("ob is instance of D");
	System.out.println();
ob = c; // A reference to c
	System.out.println("ob now refers to c");

if(ob instanceof D)
	System.out.println("ob can be cast to D");
else
	System.out.println("ob cannot be cast to D");

if(ob instanceof A)
	System.out.println("ob can be cast to A");
	System.out.println();

// all objects can be cast to Object
if(a instanceof Object)
	System.out.println("a may be cast to Object");

if(b instanceof Object)
	System.out.println("b may be cast to Object");

if(c instanceof Object)
	System.out.println("c may be cast to Object");

if(d instanceof Object)
	System.out.println("d may be cast to Object");
	}
}
 

Output:

a is instance of A
b is instance of B
c is instance of C
c can be cast to A

ob now refers to d
ob is instance of D

ob now refers to c
ob cannot be cast to D
ob can be cast to A

a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object
Press any key to continue . . .
 

The instanceof operator isn't needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you’re writing generalized routines that operate on objects of a complex class hierarchy.

Another important example of instanceof operator

In the below example  except for the main class, we have also defined three classes and one interface. We have defined a parent class called Vehicle and two subclasses called Car and MotorCycle, perspectively. Also, we have defined an interface called DriveCar, which is implemented only by class Car. Then we use the operator instanceof in different cases so as to check the hierarchy among the different types of classes.

Program:

// Demonstrate instanceof operator.
public class InstanceofExample {
	public static void main(String[] args) {

		Vehicle vehicle = new Vehicle();
		Car car = new Car();
		MotorCycle moto = new MotorCycle();

		// Those will evaluate to true
		System.out.println("vehicle instanceof Vehicle: "
				+ (vehicle instanceof Vehicle));
		System.out.println("car instanceof Vehicle: "
				+ (car instanceof Vehicle));
		System.out.println("car instanceof Car: " + (car instanceof Car));
		System.out.println("car instanceof DriveCar: "
				+ (car instanceof DriveCar));
		System.out.println("moto instanceof Vehicle: "
				+ (moto instanceof Vehicle));
		System.out.println("moto instanceof MotorCycle: "
				+ (moto instanceof MotorCycle));

		// those will evaluate to false
		System.out.println("vehicle instanceof Car: "
				+ (vehicle instanceof Car));
		System.out.println("vehicle instanceof DriveCar: "
				+ (vehicle instanceof DriveCar));
		System.out.println("moto instanceof DriveCar: "
				+ (moto instanceof DriveCar));

		// those will evaluate to false, as the object car is null
		car = null;
		System.out.println("(car=null) instanceof Vehicle: "
				+ (car instanceof Vehicle));
		System.out.println("(car=null) instanceof Car: "
				+ (car instanceof Car));
	}

}

class Vehicle {
}

class Car extends Vehicle implements DriveCar {
}

class MotorCycle extends Vehicle {
}

interface DriveCar {
}
 

Output:

vehicle instanceof Vehicle: true
car instanceof Vehicle: true
car instanceof Car: true
car instanceof DriveCar: true
moto instanceof Vehicle: true
moto instanceof MotorCycle: true
vehicle instanceof Car: false
vehicle instanceof DriveCar: false
moto instanceof DriveCar: false
(car=null) instanceof Vehicle: false
(car=null) instanceof Car: false
Press any key to continue . . .
 

Real world example instanceof in java

Followind is a real use of instanceof keyword by the example given below.

Program:

interface Printable{}
class ClassA implements Printable{
public void a(){
	System.out.println("a method");
	}
}

class ClassB implements Printable{
public void b(){
	System.out.println("b method");
	}
}

class Call{
void invoke(Printable p){//upcasting
	if(p instanceof ClassA){
	ClassA a=(ClassA)p;//Downcasting
	a.a();
	}

if(p instanceof ClassB){
	ClassB b=(ClassB)p;//Downcasting
	b.b();
	}

  }
}//end of Call class

class MainClassInstanceof{
	public static void main(String args[]){
	Printable p=new ClassB();
	Call c=new Call();
	c.invoke(p);
	}
}
 

Output:

b method
Press any key to continue . . .