instanceof OperatorThe instanceof operator in Java is used to test whether an object belongs to a specific class, subclass, or interface. It returns a boolean value: true or false.
ClassCastExceptionfalse if the object is nullThe general syntax of the instanceof operator is:
// Checking object type using instanceof
objectReference instanceof ClassName
// Base class
class Animal {}
// Derived class
class Dog extends Animal {}
// Main class to test instanceof
public class TestInstanceof {
public static void main(String[] args) {
Animal a = new Dog();
// Checking relationship between object and class
System.out.println(a instanceof Dog);
System.out.println(a instanceof Animal);
}
}
true
true
The object a refers to a Dog object, so it is considered an instance of both Dog and its parent class Animal.
instanceof before type castingnull if requiredinstanceof with interfacesnullinstanceof and observe the exception