Save thirteen bytes - (null instanceof String) is false!

15 Dec 2005

Got any code like this?

if (x != null && x instanceof Foo) {
 // do something
}

Certainly the JDK does - at least, in JDK 1.4.2, PlainSocketImpl.java has a bunch of these.

But since instanceof expressions return false if the value of the relational expression is null (see JLS 2nd Ed, 15.20.2), you can simply reduce that code to:

if (x instanceof Foo) {
 // do something
}

Here's how the bytecode looks with the unnecessary null check:

   0:   aload_1
   1:   ifnull  11
   4:   aload_1
   5:   instanceof      #2; //class String
   8:   ifeq    16

and without it:

   0:   aload_1
   1:   instanceof      #2; //class String
   4:   ifeq    12

A nice little savings there - so your classfiles get smaller and your code runs a bit faster!

Of course, there's a PMD rule that checks for this. And you'll find many more code analyses of this sort in my recent book, PMD Applied. Enjoy!