Skip to content

Java instanceof operator

Java instanceof operator

1. Overview

In this article, we will discuss the Java instanceof operator with examples.

2. Java instanceof operator

The Java instanceof operator (type comparison) compares an object to a specified type. So you can use it to check if an object is an instance of a:

  1. class
  2. subclass
  3. class that implements a particular interface.

The syntax of the instance of operator is:

<object> instanceof <type>

The return type of the instance of is a boolean value: true or false.

The instance of is based on is-a relationship, meaning it depends on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. Thus, you can say “A target object is a type of its own class / inheritance class (superclass) / interface”

Also, it is unidirectional. For example, House is a Building. But Building is not a House.

2.1. instanceof example in Java

Let’s take an instanceof example to understand.

Consider the below code that contains interface Vehicle. The classes Bike and Car implements the Vehicle interface.

interface Vehicle {}
class Bike implements Vehicle {
    final int numberOfWheels = 2;
}

class Car implements Vehicle {
    final int wheelCount = 4;
}

The below getWheelCount method takes the object vehicle of type Vehicle. We use instanceof to check whether the vehicle instance is of type Car or Bike.

Since instanceof returns true or false as result, we can use it with if-else statement.

public static int getWheelCount(Vehicle vehicle) throws IllegalArgumentException {
     if (vehicle instanceof Car) {
        Car car = (Car) vehicle;
        return car.wheelCount;
     } else if (vehicle instanceof Bike) {
          Bike bike = (Bike) vehicle;
         return bike.numberOfWheels;
     } else {
         throw new IllegalArgumentException("Unrecognized vehicle");
     }
}

After checking the instance type of the object, we are casting it to the corresponding type for accessing its methods and variables.

Let’s take another example that includes both superclass and interface.

For example, the obj1 is a direct object of Vehicle and is a type of only Vehicle. However, obj2 is a type of Car, Vehicle and also Machine.

class InstanceofDemo {
    public static void main(String[] args) {

        Vehicle obj1 = new Vehicle();
        Car obj2 = new Car();

        System.out.println("obj1 instanceof Vehicle: "
            + (obj1 instanceof Vehicle)); 
        System.out.println("obj1 instanceof Car: "
            + (obj1 instanceof Car)); 
        System.out.println("obj1 instanceof Machine: "
            + (obj1 instanceof Machine)); 
        System.out.println("obj2 instanceof Machine: "
            + (obj2 instanceof Machine)); 
        System.out.println("obj2 instanceof Car: "
            + (obj2 instanceof Car)); 
        System.out.println("obj2 instanceof Machine: "
            + (obj2 instanceof Machine)); 
    }
}

class Vehicle {}
class Car extends Vehicle implements Machine {}
interface Machine {}

2.2. object instanceof java

Class Object is the root of the class hierarchy. Every class has Object as a superclass. So when you compare any instance with Object class, it would always evaluate to true.

Car car = new Car();
System.out.println(car instanceof Object); 

2.3. Java instance of null check

You can compare a null instance against a type using the instanceof operator. So, there is no need to perform null check before calling the instanceof operator.

For example, the below car variable is null, so comparing it against the type Object returns false.

Car car = null;
System.out.println(car instanceof Object); 

2.4. Java stream instanceof

You can use instanceof with stream filter. In the below example, we are filtering all the car objects from the vehicleList as below:

vehicleList.stream()
    .filter(vehicle -> vehicle instanceof Car)
    .map (vehicle -> (Car) vehicle)
    .collect(Collectors.toList());

3. Conclusion

To sum up, this article focuses on Java instanceof and its use cases. See this article on instanceof pattern matching introduced in Java 14 as a preview feature and available in Java 16 (JEP 394) as production.

Leave a Reply

Your email address will not be published. Required fields are marked *