Trusted answers to developer questions

What is the instanceof operator used for in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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);
}
}
}

RELATED TAGS

java
type
objects
interface
operators
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?