The instanceof
operator in Java is used to test whether an object is an instance of a particular class or interface. It returns true
if the object is an instance of the specified class or interface, or if it is an instance of a subclass of the specified class, directly or indirectly. Otherwise, it returns false
.
It takes into account inheritance hierarchy. If a class inherits from another class or implements an interface, an object of that class is also considered an instance of its superclass or any of its super interfaces.
When used with a null
reference, instanceof
always returns false
. This can be useful for avoiding NullPointerExceptions
when dealing with potentially null
references.
Uses
Object obj = "Hello";
if (obj instanceof String) {
System.out.println("obj is an instance of String class.");
} else {
System.out.println("obj is not an instance of String class.");
}
Using instanceof
with Inheritance:
class Animal {}
class Dog extends Animal {}
Animal animal = new Dog();
if (animal instanceof Dog) {
System.out.println("animal is an instance of Dog class.");
} else {
System.out.println("animal is not an instance of Dog class.");
}
Using instanceof
with Interfaces:
interface Printable {}
class Book implements Printable {}
Printable printable = new Book();
if (printable instanceof Book) {
System.out.println("printable is an instance of Book class.");
} else {
System.out.println("printable is not an instance of Book class.");
}
Using instanceof
with Arrays:
int[] numbers = {1, 2, 3, 4, 5};
if (numbers instanceof int[]) {
System.out.println("numbers is an instance of int[] array.");
} else {
System.out.println("numbers is not an instance of int[] array.");
}
Using instanceof
with null
:
String str = null;
if (str instanceof String) {
System.out.println("str is an instance of String class.");
} else {
System.out.println("str is not an instance of String class.");
}
Using instanceof
with Class Literals:
if (String.class instanceof Class) {
System.out.println("String.class is an instance of Class class.");
} else {
System.out.println("String.class is not an instance of Class class.");
}