Explain Codes LogoExplain Codes Logo

Is null check needed before calling instanceof?

java
instanceof
null-check
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 24, 2024
TLDR

No, a null check is not needed before using instanceof because it treats a null reference as false, thereby eliminating the risk of a NullPointerException.

if (myObject instanceof MyClass) { // We're all good to use myObject here - it's confirmed to be a non-null MyClass instance // And yeah, no NullPointerException on our watch! }

This means that the nice instanceof operator plays the role of a null safety guard for you.

Deep dive into instanceof and null check

Straightforward, right? However, let's talk turkey and explore this magic operator more thoroughly. So sit tight, things are about to get instanceof-ey.

Pattern Matching and instanceof

Starting from Java 17, we have a nifty feature called pattern matching for instanceof. Now, that's what I call leveling up!

if (myObject instanceof MyClass mc) { // mc is now a safely casted variable of type MyClass. Whoa! Talk about being two steps ahead! }

In this case, you don't need to cast the variable again after the instanceof check. This feature has clutter-cutters high fiving all over, as it allows cleaner and more straightforward code.

Class#isInstance vs instanceof

If you're a fan of alternatives, you might fancy using Class#isInstance(Object). This baby also treads the same path and treats null values as a silent pass, rather than as a reason to scream exceptions:

if (MyClass.class.isInstance(myObject)) { // The object is either a MyClass instance or null, and we're cool either way! }

Coding interviews got you sweating?

Here's an odd thing: in an interview scenario, using instanceof without preceding null checks might cause raised eyebrows, even though it's technically the Jarvis of type checks. So let's say, try to read the room (or the Zoom call?), and clarify this point with your interviewer if you're asked.

Casting null safely

No more beating around the bush, you can cast null without fearing method calls that go bump:

public class Test { static void test(A a) { System.out.println("Method called with: " + a); // Code execution at its best! } public static void main(String[] args) { Test.test((A)null); // Prints: "Method called with: null". Guess who didn't throw a fit? Yes, the JVM! } } class A {}

Invoking test((A)null) is like you saying, "Yeah, I know what I'm doing, and I'm handling this null right!"

Cleaner code: Drop the unnecessary null check

Saying no to redundant null checks before instanceof can bring several benefits to your code:

  • Readability: Less clutter, more room for logic.
  • Performance: Did someone say fewer method calls? Yes, please!
  • Conventionality: Keep up with standard Java practices.

Best coding practices involving instanceof

With all this newfound instanceof wisdom, here are some best practices to keep in mind:

  • Ensure instanceof is your type-checking samurai before casting objects.
  • Use Java 17's pattern matching feature to make your code look cooler with less redundancy.
  • Say goodbye to unneeded null checks. They’re like that third wheel where instanceof is concerned!