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

1. instanceof keyword:

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

1.1 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,

1.2 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

2. Examples on instanceof operator

  1. instanceof operator example
  2. instanceof operator with Inheritance
  3. instanceof operator with interface example in Inheritance
  4. instanceof operator with null object
  5. Down-casting and instanceof operator

2.1 instanceof operator example:

  • A simple Employee class, checking Employee object using instanceof operator/keyword

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.2 instanceof operator in Inheritance

  • Let us understand an example with Inheritance concept

Car.java and 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

2.3 instanceof operator with interface example in Inheritance

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

Car.java and 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

2.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

2.5 Down-casting and instanceof operator

  • Whenever super-class’ object is assigned to sub-class reference-type, then compiler throws a compile-time error stating reason
  • Compile-time error :-Type mismatch: cannot convert from <super-class-type> to <sub-class-type>
Car newCar = new Vehicle();
  • But explicit type-casting i.e.; down-casting in this example, leads to successful compilation but ClassCastException exception is thrown during execution/runtime
Car newCar = (Car) new Vehicle();
  • Runtime-time error :- java.lang.ClassCastException: Vehicle cannot be cast to Car
  • Solution :- But cautiously checking/comparing, before assigning or down-casting using instanceof operator, neither raises compile-time error nor exception is thrown at execution/runtime

Car.java and Vehicle.java

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

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

public class Car extends Vehicle {

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

	public static void main(String[] args) {

		// creating an object of type Car and
		// 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 !!");
		}
		else{

			System.out.println("down-casting NOT possible !!");
		}
	}
}

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/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 during compilation and class-cast exception during execution/runtime

3. Point to be remember about instanceof operator:

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

That’s all about instanceof operator in Java

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - final keyword with example
Java - Interface v/s Abstract Classes