instanceof Operator

The instanceof operator is a binary operator that checks if a reference variable is an instance of a specific class or a subclass. It also works for interfaces, verifying whether an object implements a given interface.

Characteristics of instanceof

  • Returns true if the object belongs to the specified class, subclass, or implements the given interface.
  • Returns false if the object is null.
  • Prevents ClassCastException by ensuring safe type conversion.

Syntax

  • object – The reference variable to be tested.
  • ClassName – The class or interface to check against.
  • Returns true if object is an instance of ClassName, otherwise false.

Example

  • myDog instanceof Dog: true, because myDog is an instance of Dog.
  • myDog instanceof Animal: true, since Dog is a subclass of Animal.
  • myDog instanceof Object: true, because all Java classes implicitly extend Object.

Usage

Using instanceof with Interfaces

In Java, an interface defines a contract that classes can implement. The instanceof operator can check whether an object implements a particular interface.

  • person instanceof Human: true, since person is an instance of Human.
  • person instanceof Walkable: true, because Human implements the Walkable interface.

Handling Null References with instanceof

If a reference variable is null, instanceof never throws a NullPointerException, it simply returns false.

  • Since text is null, it does not refer to any object, so instanceof safely returns false instead of throwing an exception.

Using instanceof Before Type Casting

The instanceof operator helps ensure safe downcasting, which prevents runtime exceptions.

  • The instanceof check ensures myAnimal is actually a Dog before performing the downcast ((Dog) myAnimal).
  • Without instanceof, if myAnimal pointed to a different subclass of Animal, it could result in a ClassCastException.