☕ Java Beginner

What is the instanceof operator in Java?

Why Interviewers Ask This

This is a classic screening question for Java roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

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.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Java answers easy to follow.