BCA / B.Tech 9 min read

instanceof Operator

The `instanceof` Operator in Java:

The `instanceof` operator is a type-comparison operator used to test whether an object is an instance of a particular class, a subclass, or an interface. It returns a boolean value: `true` if the object is an instance of the specified type, and `false` otherwise.

Syntax: objectReference instanceof ClassOrInterfaceName;

Usage and Benefits:

The primary use of `instanceof` is for safe type casting. It helps prevent a `ClassCastException` that would occur at runtime if you tried to cast an object to an incompatible type. By checking the type before casting, you ensure the operation is valid.


Object obj = "Hello";
if (obj instanceof String) {
    String str = (String) obj; // Safe cast
    System.out.println(str.length());
}
        

If the object reference is `null`, the `instanceof` check will always return `false`.