Java instanceof Operator

Java instanceof operator (also called type comparison operator) is used to test whether the specified object is an instance of the specified type (class, subclass, or interface).

The instanceof returns –

  • true – if the variable is an instance of the specified class, its parent class or implements specified interface, or its parent interface
  • false – if the variable is no instance of the class or implement the interface, or the variable is null.
HashMap map = new HashMap();

assertTrue( map instanceof Map );
assertTrue( map instanceof AbstractMap );
assertFalse( map instanceof List );

map = null;
assertFalse( map instanceof Map );

1. Syntax of instanceof Operator

The instanceof operator tests variables to the specified type. Variable is written on the left-hand side of the operator, and type is given on the right side of the operator.

boolean value = variable instanceof ClassType;

//or
 
if(variable instanceof ClassType) {
//perform some action
}

2. The instanceof Operator does not need an Explicit null Check

In Java, null is a type so we do not need to check for NullPointerException when using the instanceof operator. The instanceof does it internally for us.

if(map != null && map instanceof Map) {
      //some action
}

In the previous example, we do not need to make an explicit null check. The correct way to write the expression is:

if(map instanceof Map) {   //null check is implicit
  //some action
}

3. Using instanceof with an Array

In Java, arrays are also considered objects and have associated fields and methods. So we can use instanceof operator with arrays as well.

Primitive arrays are instances of Object and self-type. e.g. int[] is type of Object and int[]. Both comparisons return true.

int[] intArr = new int[0];

Assertions.assertTrue(intArr instanceof Object);
Assertions.assertTrue(intArr instanceof int[]);

Object arrays are types of Object, Object[], classtype array, and parent class type array. e.g. Integer[] is type of Object, Object[], Integer[] and Number[] (Integer extends Number).

Integer[] integerArr = new Integer[0];

Assertions.assertTrue(integerArr instanceof Object);
Assertions.assertTrue(integerArr instanceof Object[]);
Assertions.assertTrue(integerArr instanceof Integer[]);
Assertions.assertTrue(integerArr instanceof Number[]);

4. When to Use?

A real-life example of using instanceof operator can be typecasting a variable to another type. The instanceof operator helps in avoiding ClassCastException in runtime.

Consider the following example where we are trying to typecast a list to LinkedList class, where the original variable is of type ArrayList. It will throw ClassCastException.

List<String> list = new ArrayList<>();
LinkedList<String> linkedList = (LinkedList) list;   //ClassCastException

To correctly cast the variable, we can use instanceof operator. It will not result in ClassCastException.

List<String> list = new ArrayList<>();

if(list instanceof LinkedList) {

  LinkedList<String> linkedList = (LinkedList) list;
  //other actions
} else if(list instanceof ArrayList) {

  ArrayList<String> arrayList = (ArrayList) list;
  //other actions
}

Since Java 14, instanceof operator supports pattern matching. We can rewrite the above expression more concisely:

List<String> list = new ArrayList<>();

if(list instanceof LinkedList linkedList) {
  
  //use linkedlist variable here
} else if(list instanceof ArrayList arrayList) {
  
  //use arraylist variable here
}

Drop me your questions related to the instanceof operator used for type comparison.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode