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.

Example:

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, 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
 
Using the instanceof when the object is null:
 
class Test {

  public static void main(String[] args){
    Car car = null;
    System.out.println(car instanceof Car);
  }
}
Output: false
 
That’s it!

Leave a Reply

Your email address will not be published.