Introduction To Instanceof Operator In Java

Introduction

This article describes the instanceof operator in Java.

Description

The instanceof operator allows you determine the type of an object. The instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It takes an object on the left side of the operator and a type on the right side of the operator and returns a Boolean value indicating whether the object belongs to that type or not.

It is also known as a type comparison operator since it compares the instance types. They return a Boolean value (in other words either true or false). If we apply the instanceof operator with any variable that has a null value then it returns false.

Example

In this example, a class "A" is created to show the instance reference.

class A

{

    public static void main(String args[])

    {

        A a=new A();

        System.out.println(a instanceof A);
        //
returns
true

    }

}

Output

fig-1.jpg

2. Example

An object of subclass type is also a type of the parent class

For example, if the Apple class extends the Fruit then the Apple object can be referred to by either the Apple or Fruit class.

class Fruit

{

}

class Apple extends Fruit

{

    // Apple inherit Fruit

    public static void main(String args[])

    {

        Apple app=new Apple();

        System.out.println(app instanceof Fruit);//returns true

    }

}

Output

fig-2.jpg

3. Example

Instanceof compares the type of the Operator

The instanceof operator compares an object with the specified type.

The following program, InstanceofEx, defines a parent class (named Main), a simple interface (named MyInterface), and a child class (named Derived) that inherits from the Main and implements the interface.

class InstanceofEx

{

    public static void main(String args[])

    {

        Main m1 = new Main();

        Main m2 = new Derived();

        System.out.println("m1 instanceof Main: "+ (m1 instanceof Main));

        System.out.println("m1 instanceof Derived: "+ (m1 instanceof Derived));

        System.out.println("m1 instanceof MyInterface: "+ (m1 instanceof MyInterface));

        System.out.println("m2 instanceof Main: "+ (m2 instanceof Main));

        System.out.println("m2 instanceof Derived: "+ (m2 instanceof Derived));

        System.out.println("m2 instanceof MyInterface: "+ (m2 instanceof MyInterface));

    }

}

class Main {}

class Derived extends Main implements MyInterface {}

interface MyInterface {}

Output:

fig-3.jpg

Note: When we use the instanceof operator, always remember that null is not an instance of anything.

Up Next
    Ebook Download
    View all
    Learn
    View all