Understanding instanceof operator in Java

instanceof operator in java is used to compare object reference variables. It can be used to check if the object referenced by any object reference variable is of a particular type. This is also known as the type comparison operator. The most simple usage is like:

In the above snippet, there is an object reference variable s, which references to a String object in the heap. To verify the type of this String object s, the statement, s instanceof String, checks if the object to which the reference variable s points, is of the type String.

The instanceof operator evaluates to return either a true or false.

This is a very straightforward scenario. There might be some unusual scenarios where you have to deal with object array of different types and you need to perform operations specific to each of the object types.

Multiple usage of instanceof operator is usually not preferable, yet there are exceptions to that. One such exception might be the case where there are multiple table mappings configured in hibernate, such that when we perform the JOIN of person and address entities, and select both the entities while framing the criteria query, it generates the SQL as:

Note that, such criteria when executed will return a resultList (say it as list xList) with each list item being an another list (say it as list yList) having individual person and its associated address object. So there might be same persons in the xList list items with different address objects associated. With that said, the list xList looks should something like:

Note that the two person objects in xList list items above (each xList list item is again a list, we said it to be yList) are the same, while the address objects associated are different, which implies that the same person has two different addresses associated in this case.

Now there might be scenarios where you need to process each entity object (Person and Address) in yList differently based on their Type.

Such scenarios are very much expected, especially when we are dealing with a web service application and we need to structure the service response object.


Before we wrap up this article, let’s check out the below snippet to help you clarify the concept much better.

Let’s try understand any one of the above if conditions –

In the above snippet, note that reference a points to an object B in the heap. So definitely we can say “B IS-A B” and the condition is true.

However, in the below snippet:

reference a1 points to an object A in the heap, and “A is not a subtype of B”. Hence the condition is false.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.