☕ Java Beginner

What is the instanceof operator in Java?

Answer

The instanceof operator checks whether an object is an instance of a specific class or implements a specific interface, returning a boolean. Example: if (animal instanceof Dog) { Dog dog = (Dog) animal; }. It is commonly used before a cast to avoid ClassCastException. In Java 16+, pattern matching for instanceof was standardized: if (animal instanceof Dog dog) { dog.bark(); } — the variable dog is automatically declared and cast within the if block, eliminating the explicit cast. instanceof returns false if the reference is null.