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 isnull
. - Prevents
ClassCastException
by 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
true
ifobject
is 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, becausemyDog
is an instance ofDog
.myDog instanceof Animal
: true, sinceDog
is 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, sinceperson
is an instance ofHuman
.person instanceof Walkable
: true, becauseHuman
implements theWalkable
interface.
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
text
isnull
, it does not refer to any object, soinstanceof
safely returnsfalse
instead 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
instanceof
check ensuresmyAnimal
is actually aDog
before performing the downcast ((Dog) myAnimal
). - Without
instanceof
, ifmyAnimal
pointed to a different subclass ofAnimal
, it could result in aClassCastException
.