instanceof Operator in Java

The instanceof operator in java is mainly used to check whether an object is an instance of a specific class or not. It is also known as comparison operator because it compares the instance with type.

The instanceof operator works by checking the type of the object at runtime. It traverses the class hierarchy to determine whether the object is an instance of the specified type or any of its subtypes. If the object is an instance of the specified type or a subtype, the result is true; otherwise, it's false.

  • The instanceof operator provides a way to find type information of an object at runtime.
  • It is a boolean operator and returns either true or false depending upon whether object is an instance of given class or not.
  • instanceof operator is also used for type casting object at runtime.
  • instanceof operator will return false if we apply instanceof operator to null.
  • All java classes inherits from Object class. So, instances of all the classes are also an instance of the Object class.
  • instanceof returning false for null object.

Syntax of instanceof operator

The syntax of the instanceof operator is as follows:
object instanceof type

Here, object is the reference to the object being tested, and type is the class or interface being checked against. The result of the instanceof operator is a boolean value (true or false) indicating whether the object is an instance of the specified type.

// Example usage of the instanceof operator
if (myObject instanceof MyClass) {
    // Code to execute if myObject is an instance of MyClass
} else {
    // Code to execute if myObject is not an instance of MyClass
}

Example java program for instanceof operator

class Shirt {
}
public class InstanceofOperator {
    public static void main(String[] args) {
        // Basic data types
        String tcc = "TechCrashCourse";
        // User defined object
        Shirt shirt = new Shirt();

        // Check if tcc is an instance of String
        boolean isString = tcc instanceof String;
        System.out.println("isString: " + isString);

        // Check if shirt is an instance of Shirt
        boolean isShirt = shirt instanceof Shirt;
        System.out.println("isShirt: " + isShirt);
    }
}
Output
isString: true
isShirt: true

In the above program, we have created a String variable named tcc and an object shirt of the Shirt class.
We are using instanceof operator to check whether tcc is an instance of String or not and whether shirt is an instance of class Shirt or not. In both cases instanceof operator returned true.


Java instanceof operator during inheritance

We can use instanceof operator in java to check if an object is an instance of child class or parent class.

  • An object of child type is also an instance of parent class.
  • An object of parent class type is not an instance of child class.

// Parent class
class Animal {
}

// Child class
class Tiger extends Animal {
}

public class InstanceofOperator {
    public static void main(String[] args) {
        // Create object of parent class
        Animal a = new Animal();
        // Create object of child class
        Tiger t = new Tiger();

        // Check if t is an instance of Tiger(child)
        System.out.println(t instanceof Tiger); // true
        // Check if t is an instance of Animal(parent)
        System.out.println(t instanceof Animal); // true

        // Check if a is an instance of Tiger(child)
        System.out.println(a instanceof Tiger); // false
        // Check if a is an instance of Animal(parent)
        System.out.println(a instanceof Animal); // true
    }
}
Output
true
true
false
true

In the above program, we have created a child class Tiger which inherits from the parent class Animal. We have created an object of Animal and Tiger class named "a" and "t" respectively.

Inside main method, we are using instanceof operator to check that a child class instance(t) is also an instance of parent class whereas an instance of parent class(a) is not an instance of child class.


Java instanceof operator in interface

The instanceof operator in java can also be used to check whether an object of a class is also an instance of the interface implemented by the class.

// Interface
interface Runner {
    void run();
}

class Tiger implements Runner {
    public void run() {
        System.out.println("Tiger is running.");
    }
}

public class InstanceofOperator {
    public static void main(String[] args) {
        // Create object of Tiger class
        Tiger t = new Tiger();

        // Check if t is an instance of Tiger
        System.out.println(t instanceof Tiger);
        // Check if t is an instance of Runner
        System.out.println(t instanceof Runner);
        t.run();
    }
}
Output
true
true
Tiger is running.

In the above program, the Tiger class implements Runner interface. Object t is an instance of Tiger class and instanceof operator checks that object t is also an instance of interface Runner.


Best Practices and Considerations of Using instanceof Operator

  • Limit Usage in Object-Oriented Designs : While the instanceof operator can be useful in certain scenarios, relying on it too heavily can be an indicator of a design issue. In object-oriented programming, polymorphism and proper class hierarchies often provide more elegant solutions.

  • Favor Polymorphism : Whenever possible, favor polymorphism and design your classes and interfaces to allow for flexible and extensible behavior. This can reduce the need for explicit type checking.

  • Encapsulate Type-Specific Behavior : If you find yourself using instanceof frequently, consider encapsulating type-specific behavior within the classes themselves. This promotes a more object-oriented approach.
    class Animal {
        void makeSound() {
            // Default sound
        }
    }
    
    class Dog extends Animal {
        void makeSound() {
            System.out.println("Bark");
        }
    }
    
    class Cat extends Animal {
        void makeSound() {
            System.out.println("Meow");
        }
    }
    

  • Combine with Polymorphism : The instanceof operator can be used in conjunction with polymorphism to handle specific cases while still benefiting from the flexibility of polymorphic designs.
    interface Shape {
        void draw();
    }
    
    class Circle implements Shape {
        public void draw() {
            System.out.println("Drawing a Circle");
        }
    }
    
    class Square implements Shape {
        public void draw() {
            System.out.println("Drawing a Square");
        }
    }
    
    class DrawingApp {
        void drawShape(Shape shape) {
            if (shape instanceof Circle) {
                Circle circle = (Circle) shape;
                // Handle Circle-specific behavior
            }
            // Common drawing logic for all shapes
            shape.draw();
        }
    }
    

Conclusion

The instanceof operator in Java is a valuable tool for checking object types at runtime, enabling developers to make decisions based on the actual class or interface of an object. While it can be useful in certain scenarios, it's essential to use it judiciously and be aware of potential design improvements through polymorphism and encapsulation. By understanding the syntax, use cases, and best practices of the instanceof operator, Java developers can write more robust, flexible, and maintainable code.