Java instanceof operator
In this article, we will take a deep dive into java instanceof
operator, its benefit, syntax and how to use it to avoid ClassCastException with ample examples.
Java
instanceof
operator is used to check if an object is of the a particular type or not.
In other words, it is used to test and confirm if an object is an instance of a class.
Since, instanceof
is a reserved word, it is a java keyword.
Syntax
instanceof
is a binary operator, in that, it requires two operands.
First is the object whose type needs to be checked. Second is the class or interface, with which it will be checked.
instanceof
returns a boolean
value. Its syntax is
object instanceof className
instanceof
will return true
, if
1. object is of same type as the class.
2. object is of subclass of the class.
3. object is of a class that implements this interface, if the type on the right is a java interface.
It will return false
, if the object to be checked is null
.
instanceof
will result in a compiler error, “Incompatible conditional operand types”, if
1. Class name is null
.
2. Object on the left and class or interface on the right are unrelated, such as an integer and a string.
3. Comparing generic collection type with a generic Collection class.
In this case, the error will be “Cannot perform instanceof check against parameterized type”.
instanceof example
Below is a basic example of java instanceof
operator.
It defines a string object and checks if it is an instance of String class
String s = "codippa.com"; boolean in = s instanceof String; System.out.print(in); // true
instanceof with inheritance
instanceof
checks that the object on the left side is an instance of the class given on the right or one of its subclass. Thus, it will return true
, if the object is of the same type or any of the subclasses. Example,
Consider the below hierarchy of classes
class TwoWheeler { } class BiCycle extends TwoWheeler { }
Now, below is the usage of instanceof
BiCycle b = new BiCycle(); b instanceof BiCycle // true b instanceof TwoWheeler // true
Since BiCycle
is an instance of BiCycle
and TwoWheeler
(parent class)
Also, look at the below code snippet
TwoWheeler t = new TwoWheeler(); t instanceof TwoWheeler // true t instanceof BiCycle // false
Second statement is false
, because TwoWheeler
(parent) is not an instance of BiCycle
(child).
Below code snippet further explains the behavior of
instanceof
operator in case of polymorphism.
// parent reference TwoWheeler b = new BiCycle(); b instanceof TwoWheeler // true b instanceof BiCycle // true
In the above example, reference is of parent class, while actual object is of child class.
Since BiCycle
is an instance of TwoWheeler
(parent), so the first statement is true
.
Since BiCycle
is also an instance of itself, second statement is true
.
Thus, instanceof
will return true
, if the object and the class have an is-a relationship.
instanceof with Interface
If an object implements an interface, instanceof
considers the object to be of the same type as the interface. That is, it returns true
if the object implements it. Example,
Consider below hierarchy.
interface Driver { } class DisplayDriver implements Driver { }
And below code snippet to understand instanceof
DisplayDriver d = new DisplayDriver(); d instanceof DisplayDriver // true d instanceof Driver // true
Similarly, if the reference type is an interface and object is the implementing class as below, behavior of instanceof
is
Driver d = new DisplayDriver(); d instanceof DisplayDriver // true d instanceof Driver // true
This is because actual object is of type DisplayDriver
.
Thus, instanceof
will return true
, if the object and the interface have an is-a relationship.
instanceof with null
When null
is checked with a class type, instanceof
will return false
. This is because null
is not an object and hence it does not belong to any class. Example,
null instanceof String null instanceof Driver null instanceof Integer
All these will be false
.
In java, every class is indirectly a subclass of
java.lang.Object
class. Thus, when Object
is used as the class type with instanceof
, it will always return true
. Example,
Driver d = new DeviceDriver(); BiCycle b = new BiCycle(); String s = "codippa"; s instanceof Object b instanceof Object d instanceof Object
All will be true
.
instanceof benefit
instanceof
operator is excessively used to avoid ClassCastException in java.
Following are the the cases where ClassCastException
can occur
1. Trying to cast a parent class object to a child class.
2. Casting an object to invalid type, such as casting an Object
to String
.
3. Adding an object to a non-generic collection and then trying to cast it to an invalid type.
With instanceof
, this can be avoided by verifying the type of object before casting. Example,
TwoWheeler w = new TwoWheeler(); BiCycle b = (BiCycle)w;
Above code will raise a ClassCastException
and it can be avoided with instanceof
operator as
TwoWheeler w = new TwoWheeler(); if(w instanceof BiCycle) { // false BiCycle b = (BiCycle)w; }
Pattern matching with instanceof
If you look at the above code, first we check if an object is of given type with instanceof
operator, then, in order to use it, we need to cast and assign the object to a new variable.
To simplify this, java 16 introduced Pattern matching for instanceof
operator, where we can declare a variable after instanceof.
This enables us to remove explicit variable declaration statement as shown below.
TwoWheeler w = new TwoWheeler(); if(w instanceof BiCycle b) { // use b directly }
The variable after instanceof
is called binding variable.
Object being tested is assigned to the binding variable only when the result of instanceof
evaluates to true
.
This was a preview feature in java 14 but has been added to java 16.
Conclusion
To conclude, instanceof
is used to test or check if an object is of a particular class type or not.
instanceof
checks for is-a relationship between the object and class.
Thus, it will return true
, if
the object is of exact same class type,
or its subclass,
or if the type(on the right) is an interface, then the object implements it.