The instanceof operator checks whether an object is an instance of a specific class or any of its parent classes. It returns true or false.
Animal a = new Dog();
System.out.println(a instanceof Dog);
System.out.println(a instanceof Animal);
System.out.println(a instanceof Cat);
This prints true, true, false. The object is a Dog, which is also an Animal, but it is not a Cat.
You'll use instanceof before casting a parent-type variable down to a child type. Without checking first, you risk a ClassCastException at runtime.
Since Java , you can combine the check and cast in one step with pattern matching:
if (a instanceof Dog d) {
d.bark();
}
This checks the type and creates a Dog variable d in a single expression.