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
trueif the object belongs to the specified class, subclass, or implements the given interface. - Returns
falseif the object isnull. - Prevents
ClassCastExceptionby ensuring safe type conversion.
Syntax
|
1 |
object instanceof ClassName |
object– The reference variable to be tested.ClassName– The class or interface to check against.- Returns
trueifobjectis an instance ofClassName, otherwisefalse.
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Animal {} class Dog extends Animal {} public class InstanceofExample { public static void main(String[] args) { Dog myDog = new Dog(); System.out.println(myDog instanceof Dog); // true System.out.println(myDog instanceof Animal); // true System.out.println(myDog instanceof Object); // true } } |
myDog instanceof Dog: true, becausemyDogis an instance ofDog.myDog instanceof Animal: true, sinceDogis a subclass ofAnimal.myDog instanceof Object: true, because all Java classes implicitly extendObject.
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
interface Walkable {} class Human implements Walkable {} public class InterfaceInstanceofExample { public static void main(String[] args) { Human person = new Human(); System.out.println(person instanceof Human); // true System.out.println(person instanceof Walkable); // true } } |
person instanceof Human: true, sincepersonis an instance ofHuman.person instanceof Walkable: true, becauseHumanimplements theWalkableinterface.
Handling Null References with instanceof
If a reference variable is null, instanceof never throws a NullPointerException, it simply returns false.
|
1 2 |
String text = null; System.out.println(text instanceof String); // false |
- Since
textisnull, it does not refer to any object, soinstanceofsafely returnsfalseinstead of throwing an exception.
Using instanceof Before Type Casting
The instanceof operator helps ensure safe downcasting, which prevents runtime exceptions.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Animal {} class Dog extends Animal { void bark() { System.out.println("Woof! Woof!"); } } public class SafeDowncastingExample { public static void main(String[] args) { Animal myAnimal = new Dog(); // Upcasting if (myAnimal instanceof Dog) { // Check before downcasting Dog myDog = (Dog) myAnimal; // Safe Downcasting myDog.bark(); // Woof! Woof! } } } |
- The
instanceofcheck ensuresmyAnimalis actually aDogbefore performing the downcast ((Dog) myAnimal). - Without
instanceof, ifmyAnimalpointed to a different subclass ofAnimal, it could result in aClassCastException.