What is the instanceof operator used for in Java?

An instanceof in Java is a comparison operator which, given an object instance, checks whether that instance is of a specified type (class/sub-class/interface) or not. Just like other comparison operators, it returns true or false.

Comparing any object instance with a null type through instanceof operator returns a false.

svg viewer

Examples

instanceof operators behave differently between cases.

1. String data type:

class Simple{
public static void main(String args[]){
String str1 = "Educative!";
if (str1 instanceof String)
System.out.println("str1 is instance of String");
else
System.out.println("str1 is NOT instance of String");
}
}

2. Inherited classes:

class Animal { }
class Mammal extends Animal { }
class instanceofTest {
public static void main(String[] args) {
Mammal mobj = new Mammal();
Animal aobj = new Animal();
// Is `child` class instance of `child` class?
if (mobj instanceof Mammal)
System.out.println("mobj is instance of Mammal");
else
System.out.println("mobj is NOT instance of Mammal");
// Is `child` class instance of `parent` class?
if (mobj instanceof Animal)
System.out.println("mobj is instance of Animal");
else
System.out.println("mobj is NOT instance of Animal");
// Is `parent` class instance of `child` class?
if (aobj instanceof Mammal)
System.out.println("mobj is instance of Animal");
else
System.out.println("mobj is NOT instance of Animal");
}
}

Application

Suppose we create a parent class type reference pointing to an object of child class type. The parent reference wants to access the child object’s data. instanceof can be used to check the validity of the reference to the object, before we actually access the data. Have a look at the following snippet of code:

class Animal {
String name = "Animal";
}
class Mammal extends Animal {
String name = "Mammal";
}
class ApplicationTest {
public static void main(String[] args) {
Animal child = new Mammal();
Animal parent = child;
// using instance of to check validity before
// typecasting
if(parent instanceof Mammal) {
System.out.println("Name of accessed class is: "
+ ((Mammal)parent).name);
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved