← Back to Chapters

Java instanceof Operator

? Java instanceof Operator

? Quick Overview

The 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.

? Key Concepts

  • Works only with reference types (objects)
  • Used mainly in inheritance and polymorphism
  • Helps avoid ClassCastException
  • Returns false if the object is null

? Syntax / Theory

The general syntax of the instanceof operator is:

? View Code Example
// Checking object type using instanceof
objectReference instanceof ClassName

? Code Example(s)

? View Code Example
// 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);
}
}

? Live Output / Explanation

Output

true
true

The object a refers to a Dog object, so it is considered an instance of both Dog and its parent class Animal.

✅ Tips & Best Practices

  • Use instanceof before type casting
  • Avoid overusing it in place of polymorphism
  • Always check for null if required
  • Prefer method overriding over type checks

? Try It Yourself

  • Create a class hierarchy and test instanceof with interfaces
  • Check the result when the object reference is null
  • Try invalid casting without instanceof and observe the exception