Java instanceof Operator

The Java instanceof operator can be used to test if an object is of a specified type. The result can be either true or false. Let’s see a couple examples. 

Example 1

class Vehicle {
  // ...
}

class Car extends Vehicle {
  // ...
}

class Test {
    
  public static void main(String[] args){
    Car car = new Car();

    System.out.println(car instanceof Car);
    System.out.println(car instanceof Vehicle);
  }
}
Output: true true
 
The above example shows that an object of subclass type is also a superclass type. The instanceof operator works on the principle of the is-a relationship. In this case, the Car is a Vehicle.
 
In Java, every class is derived from the Object class. So, every class is an instance of the Object class.
class Vehicle {
  // ...
}

class Car extends Vehicle {
  // ...
}

class Test {
   
  public static void main(String[] args){
    Car car = new Car();

    System.out.println(car instanceof Car);
    System.out.println(car instanceof Vehicle);
    System.out.println(car instanceof Object);
  }
}
Output: true true true

Example 2

In this example, the instanceof operator is used with an object that is assigned a null value.

class Test {

  public static void main(String[] args){
    Car car = null;
    System.out.println(car instanceof Car);
  }
}
Output: false
 
I hope this tutorial was helpful to you. To learn more, check out other Java tutorials for beginners

Leave a Reply

Your email address will not be published.