Java instanceof Operator
The instanceof
operator in Java is used to test whether an object is an instance of a specific class or a subclass thereof. It is a binary operator that returns a boolean value: true
if the object is an instance of the specified class or interface, and false
otherwise. This operator is particularly useful in scenarios where you need to ensure the type of an object before performing operations on it.
Syntax
object instanceof ClassName
- object: The reference variable or object you want to test.
- ClassName: The class or interface against which the object is being tested.
Example of instanceof
Operator
Here’s a simple example to demonstrate how the instanceof
operator works:
class Animal {
// Base class
}
class Dog extends Animal {
// Dog is a subclass of Animal
}
class Cat extends Animal {
// Cat is also a subclass of Animal
}
public class InstanceofExample {
public static void main(String[] args) {
Animal animal = new Dog(); // Animal reference but Dog object
Dog dog = new Dog();
Cat cat = new Cat();
// Check if animal is an instance of Dog
if (animal instanceof Dog) {
System.out.println("animal is an instance of Dog");
} else {
System.out.println("animal is NOT an instance of Dog");
}
// Check if dog is an instance of Animal
if (dog instanceof Animal) {
System.out.println("dog is an instance of Animal");
} else {
System.out.println("dog is NOT an instance of Animal");
}
// Check if cat is an instance of Dog
if (cat instanceof Dog) {
System.out.println("cat is an instance of Dog");
} else {
System.out.println("cat is NOT an instance of Dog");
}
}
}
Output
animal is an instance of Dog
dog is an instance of Animal
cat is NOT an instance of Dog
Explanation
Creating Objects:
- An
Animal
reference variable namedanimal
points to aDog
object. - Two more objects,
dog
(of typeDog
) andcat
(of typeCat
), are created.
- An
Using
instanceof
:- The first check (
animal instanceof Dog
) evaluates totrue
becauseanimal
is actually referencing aDog
object. - The second check (
dog instanceof Animal
) also evaluates totrue
sinceDog
is a subclass ofAnimal
. - The third check (
cat instanceof Dog
) evaluates tofalse
becausecat
is of typeCat
, which is not a subclass ofDog
.
- The first check (
Important Notes
Null Values: If you use
instanceof
with anull
reference, it will always returnfalse
.Animal animal = null; System.out.println(animal instanceof Dog); // Output: false
Compile-Time Type Checking: The compiler checks the type specified in the
instanceof
operator against the object’s declared type to ensure type safety.
Summary
The instanceof
operator is a powerful tool in Java that helps you determine the runtime type of an object. It is widely used in type-checking scenarios, especially in polymorphic contexts where the exact type of an object may not be known until runtime. Understanding how to use instanceof
effectively can help you write safer and more flexible Java code.