Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 'instanceof' operator used for in Java?

People also ask

Why do we use Instanceof?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.

What is instance of a class in Java?

An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables. These variables are specific to a particular instance.

What is instance of method in Java?

Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.


instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.

Imagine:

interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}

Imagine a dog object, created with Object dog = new Dog(), then:

dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal   // true - Dog extends Animal
dog instanceof Dog      // true - Dog is Dog
dog instanceof Object   // true - Object is the parent type of all objects

However, with Object animal = new Animal();,

animal instanceof Dog // false

because Animal is a supertype of Dog and possibly less "refined".

And,

dog instanceof Cat // does not even compile!

This is because Dog is neither a subtype nor a supertype of Cat, and it also does not implement it.

Note that the variable used for dog above is of type Object. This is to show instanceof is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.

Things to note: expressionThatIsNull instanceof T is false for all Types T.


It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

Think about it this way. Say all the houses on your block were built from the same blueprints. Ten houses (objects), one set of blueprints (class definition).

instanceof is a useful tool when you've got a collection of objects and you're not sure what they are. Let's say you've got a collection of controls on a form. You want to read the checked state of whatever checkboxes are there, but you can't ask a plain old object for its checked state. Instead, you'd see if each object is a checkbox, and if it is, cast it to a checkbox and check its properties.

if (obj instanceof Checkbox)
{
    Checkbox cb = (Checkbox)obj;
    boolean state = cb.getState();
}

As described on this site:

The instanceof operator can be used to test if an object is of a specific type...

if (objectReference instanceof type)

A quick example:

String s = "Hello World!"
return s instanceof String;
//result --> true

However, applying instanceof on a null reference variable/expression returns false.

String s = null;
return s instanceof String;
//result --> false

Since a subclass is a 'type' of its superclass, you can use the instanceof to verify this...

class Parent {
    public Parent() {}
}

class Child extends Parent {
    public Child() {
        super();
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println( child instanceof Parent );
    }
}
//result --> true

I hope this helps!


This operator allows you to determine the type of an object. It returns a boolean value.

For example

package test;

import java.util.Date;
import java.util.Map;
import java.util.HashMap;

public class instanceoftest
{
    public static void main(String args[])
    {
        Map m=new HashMap();
        System.out.println("Returns a boolean value "+(m instanceof Map));
        System.out.println("Returns a boolean value "+(m instanceof HashMap));
        System.out.println("Returns a boolean value "+(m instanceof Object));
        System.out.println("Returns a boolean value "+(m instanceof Date));
    }
} 

the output is:

Returns a boolean value true
Returns a boolean value true
Returns a boolean value true
Returns a boolean value false

If source is an object variable, instanceof is a way of checking to see if it is a Button or not.