instanceof Keyword In Java

The instanceof keyword in Java is used to test whether an object is an instance of a particular class or interface. It is often used in conditional statements to determine the type of an object before performing certain operations.

Following is the basic syntax:

if (object instanceof ClassName) {
    // Code to execute if the object is an instance of ClassName
} else {
    // Code to execute if the object is not an instance of ClassName
}

Example:

public class InstanceOfDemo {
    public static void main(String[] args) {
        Object obj = "Hello, Java!";

        if (obj instanceof String) {
            System.out.println("The object is a String.");
            String str = (String) obj; // We can safely cast obj to String here
            System.out.println("Length of the string: " + str.length());
        } else {
            System.out.println("The object is not a String.");
        }
    }
}

In this example, the instanceof keyword is used to check if the object obj is an instance of the String class. If true, it then safely casts the object to a String and performs operations specific to that type. If false, it handles the case where the object is not a String.

Sharing Is Caring: