History of the Question
The instanceof operator was introduced in Java to allow checking whether an object belongs to a specific type (class or interface) before type casting. This became relevant for working with inheritance, polymorphism, and handling heterogeneous collections of objects.
The Problem
Without type checking, you can encounter ClassCastException during type casting. Improper use of instanceof can degrade the architecture of your code, leading to anti-patterns (e.g., frequent use instead of polymorphism).
Solution
The instanceof operator returns true if the object is not null and belongs to the checked type or implements the specified interface.
Sample code:
Object obj = "Hello"; if (obj instanceof String) { String str = (String) obj; System.out.println(str.toUpperCase()); }
Key features:
What will obj instanceof SomeClass return if obj == null?
instanceof always returns false if the object is null, regardless of the checked type. This is important for preventing NullPointerException.
Can instanceof be used to check for interface implementation?
Yes. instanceof is used to check whether an object implements a necessary interface, not just belongs to a specific class.
Sample code:
Runnable r = () -> {}; System.out.println(r instanceof Runnable); // true
What happens if the class is compiled with --release 16+ and pattern matching for instanceof has been introduced?
Starting from Java 16+, the instanceof operator supports pattern matching, meaning you can specify a variable directly in the check and avoid explicit casting.
Sample code:
Object obj = "Test string"; if (obj instanceof String str) { System.out.println(str.length()); }
In a large project, business processing logic was built on a series of if (obj instanceof X)..., rather than through method overriding. This complicated maintenance: the appearance of a new type required changing all checks.
Pros:
Cons:
In a similar project, an expandable hierarchy used abstract methods, and instanceof was only used for checking specific edge cases.
Pros:
Cons: