What is instanceof operator in Java with example

The Java programming language and JVM are full of hidden gems and even though I am using Java for more than a decade I still get surprised of features which I didn't know for quite some time e.g. shutdown hook, covariant method overriding, and JVM option to refresh DNS cache.  The instanceof operator is also one of the rarely known features of Java, It is used to check if an object is the instance of a particular Class or not. It returns true if the object is an instance of the class, otherwise, returns false. You might have seen usages of instanceof operator in Java while overriding equals() method. Since for checking equality of two instances, the first step is to verify whether they are the instance of the same object or not, you can use the instanceof operator there.

Some of you might have used the Class.getClass() method there but there is a slight difference between using instanceof and using getClass() while overriding equals in Java, which is also one of the tricky questions from Java Interviews.

The instanceof operator will return true even if the object is an instance of subclass but getClass() will only return true if an object is indeed an instance of specified class, in the case of subclass it would just return false.

This property can work in your favor just like it does for Hibernate, which replaces your classes with Proxies, but it can also break equals() symmetry contract (see Java Persistence with Hibernate by Gavin King).

In this article, we will see an example of the instanceof operator and learn some important points about it, so that you can not only learn how to use instanceof operator but also understand when to use the instanceof operator in Java.





Important points about instanceof operator in Java

As I told, the instanceof keyword represents a binary operator which is used to check if an object is really an instance of specified class or not. It returns true if an object is the instance of specified object or instance of subclass or subinterface of specified object, otherwise, it returns false. Let's see a couple of more points about instanceof operator in Java.

1)The syntax of instanceof operator is following:

if(anObject instanceof aClass){
   aClass cls = (aClass) anObject;
}

anObject is the instance and aClass is the class or interface e.g. Runnable, String, Number etc, a more familiar example could be like this:

if(aThread instanceof Runnable){
   Runnable r = (Runnable) aThread;
}


2) If reference variable is null then also instanceof operator doesn't throw NullPointerException, instead, it just returns false, Even if you test with the null literal it will work fine.

if (null instanceOf Runnable){
   // do something
}

This code will not throw NullPointerExcepiton but code inside if block will not get executed because instanceof will return false. that's why it's often used to prevent NullPointerException in Java, one of the techniques to avoid NullPointerException.



3) The instanceof operator is often used to prevent ClassCastExeption as well. If you remember, casting one object into another can result in ClassCastException if they are of different type, but you can prevent that by using instanceof operator before casting, as shown in the following example:

if(anObject instanceof aClass){
   aClass cls = (aClass) anObject;
}

If an object passes the instanceof check then it can be safely cast into the corresponding object, see how type casting works in Java for more details.  It can also be used to if an object belongs to parent class in complex hierarchies like Collection framework or family tree.

What is instanceof operator in Java with example



4) The instanceof operator can use to implement RTTI (runtime type identification) in Java. It returns true if the object is really an instance of the class or its subclass or subinterface as shown in the following example

Thread t = new Thread();
boolean result = false;

// true because t is instance of Thread which is subclass of Object
result = t instanceof Object; 

// true because t is object of Thread which implements Runnable interface
result = t instanceof Runnable; 

// true bease t is an instance of Thread class
result = t instanceof Thread; 

// false because Thread doesn't implement Callable
result = t instanceof Callable; 

// false because t is null;
t = null;
result = t instanceof Thread; 


5) Similar to transient and volatile, instanceof keyword is also lesser understood keyword in Java. The instanceof operator owes it's recent awareness to Hibernate, a popular object-relational mapping (ORM) framework in Java which leverage capability of this operator to implement proxies in Hibernate.


That's all about instanceof operator in Java. It's one of the fundamental operators in Java which you can use to check the type of an object at runtime. You can also prevent NullPointerExeption and ClassCastException by using this operator. The most common use of instanceof operator is in equals() method, which is also a requirement for Hibernate entity classes because when you use instnaceof then subclasses can also be equal o superclass object.


Other Core Java tutorials on Operators you may like:
  • How to use the Modulo or Remainder operator in Java? (example)
  • How to use bitwise AND, OR and NOT operator in Java? (example)
  • Difference between == and equals() in Java? (answer)
  • Difference between bitwise and logical AND, OR operator in Java? (answer)
  • Difference between bitwise and bit shift operator in Java? (answer)
  • Java Interview questions on basic operators? (questions)
  • Difference between String literal and new String() object? (answer)


References
Java language and virtual machine specification
Official Java tutorials from Oracle


2 comments: