Java: instanceof operator or keyword

In this article, we will learn instanceof operator or keyword in Java and understand how it’s help to avoid ClassCastException during type casting rather to be precise down-casting

 

instanceof keyword

instanceof operator is used to check, if an object belongs to any particular class or type during execution

Syntax:

(referenceObject instanceof classType)

 

In above expression,

  • There are 2 operands between instanceof operator
  • L.H.S operand is referenceObject and it is an object in question to test
  • R.H.S operand is class type and it is the class or interface against which above object will be evaluated

Note: R.H.S represents class or interface, anything else will raise a compile-time error

 

Above expression evaluates either true or false; let see the results,

Results:

  • Returns true, if reference object is an instance of type class
  • Returns false, if reference object is not an instance of type class
  • Always returns false for null object in comparison

Alternatively, instanceof operator referred as comparison operator because it compares an object is an instance of type class or NOT

 

1) Let us see a simple example,

Employee.java

package in.bench.resources.instance.of.operator;

public class Employee {

	public static void main(String[] args) {

		// creating an object of type Employee
		Employee emp = new Employee();

		// checking whether emp is an instance of type Employee
		if(emp instanceof Employee) {
			System.out.println("emp object is an instance of type Employee");
		}
		else{
			System.out.println("emp object is NOT an instance of type Employee");
		}
	}
}

Output:

emp object is an instance of type Employee

 

Explanation:

  • Here, we have created an object of type Employee
  • Later, checking or comparing this object with type Employee using instanceof operator
  • It returns true and prints the message in console

 

2) instanceof operator in Inheritance

Let us understand an example with Inheritance concept

Car.java & Vehicle.java

package in.bench.resources.instance.of.operator;

class Vehicle {
	// super class >> Vehicle
}

public class Car extends Vehicle {

	// sub class >> Car which extends Vehicle

	public static void main(String[] args) {

		// creating an object of type Car
		Car newCar = new Car();

		// checking whether newCar object is an instance of type Vehicle or NOT
		if(newCar instanceof Vehicle) {
			System.out.println("newCar object is an instance of type Vehicle");
		}
		else{
			System.out.println("newCar object is NOT an instance of type Vehicle");
		}
	}
}

Output:

newCar object is an instance of type Vehicle

 

Explanation:

  • There are 2 classes viz.; Vehicle and Car
  • Relationship between them is, Car IS-A Vehicle (extends)
  • Actually, we have created an object of type Car
  • But when compared with its super type class Vehicle, still it evaluates to true and corresponding message prints in the console
  • It means, if we create object of sub class type and compare with super class type using instanceof operator, evaluates true considering there exists a IS-A relationship between them

 

3) instanceof operator with interface example in Inheritance

Let us tweak above example to understand how it behaves with interface in Inheritance

Car.java & Vehicle.java

package in.bench.resources.instance.of.operator;

interface Vehicle {
	// interface >> Vehicle
}

public class Car implements Vehicle {

	// sub class >> Car which extends Vehicle

	public static void main(String[] args) {

		// creating an object of type Car
		Car newCar = new Car();

		// checking whether newCar object is an instance of type Vehicle or NOT
		if(newCar instanceof Vehicle) {
			System.out.println("newCar object is an instance of type Vehicle");
		}
		else{
			System.out.println("newCar object is NOT an instance of type Vehicle");
		}
	}
}

Output:

newCar object is an instance of type Vehicle

 

Explanation:

  • One class and another interface viz.; interface Vehicle and class Car
  • Relationship between them is, Car IS-A Vehicle (implements)
  • Actually, we have created an object of type Car
  • But when compared with its interface type Vehicle, still it evaluates to true and corresponding message prints in the console
  • It means, if we create object of sub class type and compare with interface type using instanceof operator, evaluates true considering there exists a IS-A relationship between them

 

4) instanceof operator with null object

Comparing with null object using instanceof operator –> always returns false

Let us see an example using null object

Employee.java

package in.bench.resources.instance.of.operator;

public class Employee {

	public static void main(String[] args) {

		// creating reference type of Employee
		Employee emp = null; // explicitly assigning null

		// checking whether emp object is an instance of type Employee or NOT
		if(emp instanceof Employee) {
			System.out.println("emp object is an instance of type Employee");
		}
		else{
			System.out.println("emp object is NOT an instance of type Employee");
		}
	}
}

Output:

emp object is NOT an instance of type Employee

 

Explanation:

  • A reference type emp is created and explicitly assigned with null value
  • And when compared with class type Employee using instanceof operator, returns false
  • Reason: whenever null is compared using instanceof operator –> will always returns false

 

5) Down-casting and instanceof operator

Whenever super class type object is assigned to sub class type reference, then compiler throws a compile-time error stating reason

Type mismatch: cannot convert from <super-class-type> to <sub-class-type>

Car newCar = new Vehicle();

But explicitly doing type casting i.e.; down-casting in this example, leads to compilation success but ClassCastException exception is thrown during execution

Car newCar = (Car) new Vehicle();

Error: java.lang.ClassCastException: Vehicle cannot be cast to Car

 

But cautiously checking and comparing before assigning or down-casting using instanceof operator, neither compiler complain with any error nor any exception is thrown at runtime

Car.java & Vehicle.java

package in.bench.resources.instance.of.operator;

class Vehicle {
	// super class &gt;&gt; Vehicle
}

public class Car extends Vehicle {

	// sub class &gt;&gt; Car which extends Vehicle

	public static void main(String[] args) {

		// creating an object of type Car &amp; assigning with super class type Vehicle
		Vehicle newCar = new Car();

		// checking whether newCar object is an instance of type Vehicle or NOT
		if(newCar instanceof Car) {

			Car car1 = (Car) newCar; // down-casting
			System.out.println("down-casting done !!");
			// System.out.println("newCar object is an instance of type Vehicle");
		}
		else{

			System.out.println("down-casting NOT possible !!");
			// System.out.println("newCar object is NOT an instance of type Vehicle");
		}
	}
}

Output:

down-casting done !!

 

Explanation:

  • In this example, we have created an object of sub class type and assigned it to super class type
  • Later, when we want to down-cast –> didn’t performed directly or explicitly using type casting
  • Rather we used instanceof operator to check whether down-casting is possible
  • Then, down-casted the object after instanceof operator evaluation returns true
  • This way, we can get rid of compile-time error and class cast exception during runtime

 

Point to be remember about instanceof operator:

  • instanceof operator in Java is used to test or check, if an object belongs to any class or NOT. Alternatively referred as type-comparison operator
  • Returns true, if object in question is an instance of that type
  • Returns false, if object in question is NOT an instance of that type
  • Always returns false when comparing with null object
  • It’s always a good practice to compare object with type before type-casting
  • To get rid of ClassCastException during runtime, always check type using instanceof operator
  • Very useful operator while performing up-casting & down-casting in Inheritance

That’s all about instanceof operator in Java

 

References:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.20.2

 

Read Also:

Happy Coding !!
Happy Learning !!

  • It is a beautiful explanation of all the concepts related to instanceof…Thanks for all the info. Cheers!!

    • SJ

      Thanks Nishant Patel !!