Java instanceof Operator

www.‮ditfigi‬ea.com

In Java, the instanceof operator is used to test whether an object is an instance of a particular class or interface. The instanceof operator returns a boolean value indicating whether the object on the left-hand side of the operator is an instance of the class or interface on the right-hand side of the operator.

The syntax of the instanceof operator is as follows:

object instanceof class

Here, object is the object that you want to test, and class is the class or interface that you want to test whether object is an instance of.

Here's an example of using the instanceof operator in Java:

class MyClass {
    // class body
}

class MyOtherClass extends MyClass {
    // class body
}

class MyThirdClass {
    // class body
}

public class Main {
    public static void main(String[] args) {
        MyClass obj1 = new MyClass();
        MyOtherClass obj2 = new MyOtherClass();
        MyThirdClass obj3 = new MyThirdClass();

        System.out.println(obj1 instanceof MyClass); // true
        System.out.println(obj2 instanceof MyClass); // true
        System.out.println(obj3 instanceof MyClass); // false
    }
}

In the example above, the instanceof operator is used to test whether obj1 and obj2 are instances of the MyClass class. The first two println statements will return true, as obj1 and obj2 are both instances of the MyClass class. The third println statement will return false, as obj3 is not an instance of the MyClass class.

The instanceof operator can be useful in a variety of scenarios, such as when you need to check the type of an object before performing a particular operation on it.