I am looking for a tool to find potential NPEs like the one below. In line 2, work address should have been checked against Null before calling the getZipCode() method.
I was hoping tools such as PMD, checkStyle or findBug had something for this but have not found one.
Can someone help?
Thanks much!
Person p = ...;
if(p.getWorkAddress().getZipCode() == '...'){
...
NPEs occur at runtime, so it's not surprising that static code checkers such as the ones you mention (which do not run the code) can't detect them. While there are code spots where it can be proven that an object will be null, and thus subsequent method invocations on it will cause an NPE, that's quite rare; a good IDE might even find those spots for you, so there'd be no point in additional tools.
Eclipse won't find possible NullPointerExceptions like that one. It has some (but not perfect) checking for variables that may be null, but method return types - no.
I do believe there is one IDE (Netbeans? IntelliJ?) where you could add a custom annotation to the method to indicate that it could or could not return null. However, you'll be limited to that IDE if you use it, as it's a custom annotation, one that's not available for anyone but users of the IDE.
Findbugs spots a list of possible null deference, as Tim mentioned it won't catch everything but it does a fair job at giving you a warning at many possible places. It integrates with eclipse pretty nicely too ...
(I've seen it catch a few of those in some of our existing code base & we got those fixed!)
NP: Null pointer dereference (NP_ALWAYS_NULL)
A null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed