Is null check needed before calling instanceof?

 

No, a null check is not needed before calling the instanceof operator in Java. The instanceof operator safely handles null values and will return false when used with a null reference. Here's an example:

java
public class Main { public static void main(String[] args) { String str = null; // Null check is not needed before instanceof if (str instanceof String) { System.out.println("str is an instance of String."); } else { System.out.println("str is not an instance of String."); } } }

In this example, str is a null reference, and we use instanceof to check if it's an instance of the String class. Even though str is null, the instanceof check doesn't throw any exceptions, and it evaluates to false. Therefore, the output will be:

python
str is not an instance of String.

The instanceof operator is designed to handle null values gracefully, so there's no need for an explicit null check before using it. However, you may still want to perform a null check if you have other operations to perform on the object after determining that it's not null.

Comments