instanceof Java With Examples

instanceof java keyword is used to check if an object is of some type or not. Java instanceof operator syntax is obj instanceOf Object – left side is the instance and right side is the Class name. Java instanceof operator returns boolean result.

instanceof Java

In this section, let us see how instanceof keyword can be used.

Let’s say we have some interfaces and class defined like below.

If we check the instanceof keyword with above class objects, we will see following results:

But if we reverse something, we will see different results:

instanceof is a useful tool when you’ve got a collection of objects and you’re not sure what they are.

instanceof operator vs isInstance() method

Basically, both of these do the same thing, check if an object is an instance of the same class as the other.

The instanceof operator works at compile time whereas the isInstance() method works at runtime. For example:

Let us put above method in use to demonstrate its use:

Java instanceof with array

Java array are also Object, but instanceof operator works differently when it’s used with array. For example;

But if we try something like below:

Then we get compile time error as Incompatible conditional operand types String[] and String. However below use of instanceof operator works fine.

Java instanceof example

Here is a complete example for instanceof java operator and isInstance method.

That’s all for instanceof java operator.

Reference: Oracle Documentation

By admin

Leave a Reply

%d bloggers like this: