The instanceof
operator does not need explicit null
checks, as it does not throw a NullPointerException
if the operand is null
.
At run time, the result of the instanceof
operator is true if the value of the relational expression is not null
and the reference could be cast to the reference type without raising a class cast exception.
If the operand is null
, the instanceof
operator returns false
and hence, explicit null checks are not required.
Consider the below example,
public static void main(String[] args) {
if(lista != null && lista instanceof ArrayList) { //Violation
System.out.println("In if block");
}
else {
System.out.println("In else block");
}
}
The correct usage of instanceof
is as shown below,
public static void main(String[] args) {
if(lista instanceof ArrayList){ //Correct way
System.out.println("In if block");
}
else {
System.out.println("In else block");
}
}