instanceof operator in Java Tutorial

In this section, we will learn what the instanceof operator is and how to use it in Java.

What is instanceof operator in Java?

We use explicit down casting to convince the compiler that the type of an object that we’re down casting will be matched against the variable that is going to store a reference of that object.

But there’s a chance that at runtime, the actual type of the object doesn’t match the type of the variable that stores a reference of the object.

Example:

Create a class named `Machine` and store set its body to this:

public class Machine {
    public void start(){
        System.out.println("Machine started!");
    }
}

Now create another class named `Camera` and set its body like this:

public class Camera extends Machine {
    @Override
    public void start(){
        System.out.println("Camera started!");
    }
    public void shot(){
        System.out.println("Taking a shot");
    }
}

Now set the main class to this:

public class Simple {
    public static void main(String[] args) {
        Machine machine = new Machine();
        Camera camera = (Camera) machine;
        camera.start();
        camera.shot();
    }
}

Output:

Exception in thread "main" java.lang.ClassCastException: class tuto.Machine cannot be cast to class tuto.Camera

We used the down casting here and so the compiler didn’t complain anymore. But at runtime we got error because the type that the `machine` variable is referring to (the object) is of type `Machine` and not `Camera`. For this reason, we’ve got the runtime error.

In order to stop getting runtime error because of this down casting, Java introduced the `instanceof` keyword by which we can check the type of an object at runtime against another type.

If they matched, the result of the expression will be true otherwise, it will return false.

Note: matched in the sentence above means: if the type of the object was either the same as the type (class) that we’re matching the object with, or the type of the object was one of the subclasses that are compatible with the target type.

Java instanceof operator syntax:

ObjectReference instanceof ClassName

We put a reference of the target object that we want to check its type on the left side of the `instanceof` operator and the name of the target data-type on the right side of this operator.

Example: Java instanceof and inheritance (Downcasting)

public class Simple {
    public static void main(String[] args) {
        Machine machine = new Machine();
        if (machine instanceof Camera){
            Camera camera = (Camera) machine;
            camera.start();
            camera.shot();
        }
        System.out.println("Done!");

    }
}

Output:

Done

Here we’ve used an `if` statement to check and see if the object that the `machine` variable is referring to is of compatible type to the `Camera` class. Because an object of type `Machine` is not compatible in any way with the `Camera` type, then the result of this expression is false and so the body of the `if` statement is skipped.

As you can see, we didn’t get a runtime exception this time and the program terminated successfully without crashing.

Now let’s refactor the example above to make the result of the `instacneof` expression to become true this time:

public class Simple {
    public static void main(String[] args) {
        Machine machine = new Camera();
        if (machine instanceof Camera){
            Camera camera = (Camera) machine;
            camera.start();
            camera.shot();
        }
        System.out.println("Done!");

    }
}

Output:

Camera started!

Taking a shot

Done!

Java instanceof operator and null value

If the value on the left side of the instanceof operator is a null value, then the return value of this operator will be false!

Example: instanceof and null value

package com.example.demo;

public class Main {

    public static void main(String[] args) {
        Child child = null;

        if (child instanceof Child){
            System.out.println("Yes the 'child' is an instance of the Human interface!");
        }else{
            System.out.println("No the child variable is not an instance of the Child class");
        }

    }
}

Output:

No, the child variable is not an instance of the Child class

Java instanceof and interface

The instanceof operator could also be used to check and see if an instance implemented an interface or not.

Note: please check the Java interface section if you’re not familiar with interfaces.

Example: instanceof and interface

package com.example.demo;

public interface Human {
    void printName();
}


package com.example.demo;

public class Child implements Human{
    @Override
    public void printName() {
        System.out.println("My name is John Doe");
    }
}


package com.example.demo;

public class Main {

    public static void main(String[] args) {
        Child child = new Child();
        Human human = new Child();
        if (child instanceof Human){
            System.out.println("Yes the 'child' is an instance of the Human interface!");
        }
        if (human instanceof Human){
            System.out.println("Yes the 'human' is an instance of the Human interface!");
        }
    }
}

Output:

Yes the ‘child’ is an instance of the Human interface!

Yes the ‘human’ is an instance of the Human interface!

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies