Java NullPointerException Ninja – 10 facts you need to know to avoid problems with null

1.The instanceof operator is NPE safe. So, instanceof null always returns false. It does not cause a NullPointerException. You can eliminate messy conditional code if you remember this fact.

// Unncessary code
if (data != null && data instanceof InterestingData) {

}

// Less code. Better!
if (data instanceof InterestingData) {

}

2. A null can be cast to anything without causing a NullPointerException.

// Not so good...
if (someReference == null) {
	return null;
}
else {
	return (SpecificReference) genericReference;
}

// Better.
return (SpecificReference) genericReference;

3. Autoboxing / Unboxing can cause a NullPointerException on lines that can leave you confounded. This generally happens when a Long (a wrapper type) is passed or received as an argument for a long (a primitive type) parameter. So watch out for these when trying to figure out a stack trace that does not seem to make sense.

4. a < b – This can result in a surprising NPE! This happens when wrapper types are being compared and one of them happens to be a null.

5. The equals() method should not be returning true when a null is passed to it. – The general contract of the equals method states that if null is passed to equals, false should be returned. Makes sure you do this in your code. It is easy to miss and cause a NPE instead.

6. While chained statements are nice to look at in the code, they are not NPE friendly. A single statement spead over several lines will give you the line number of the first line in the stacktrace regardless of where it occurs.

7. A reference to “this” can never be null. While it should be obvious, I have seen code that does a null check on this. Ack!

8. An awesome tip to avoid NPE is to return empty strings or empty collections rather than a null. Do this consistently across your app. You will note that a bucket load of null checks become unneeded if you do so.

9. You should put constraint checks at the beginning of your method so that the rest of your code does not have to deal with that possibility. So if someone passes in a null, things will break (IllegalArgumentException perhaps?) early in the stack rather than in some deeper location where the root problem will be difficult to identify. Aiming for fail fast behaviour is a good choice in most situations.

Or consider allowing a null pointer exception to happen if a null is passed in rather than check for a null and then doing nothing and returning. This is akin to swallowing an exception.

10. The next time someone says Java does not have pointers, ask them what causes a NullPointerException. Watch their facial expression change as they protest.

Ok, ok. I know, Java references and C++ pointers are different animals. Yes, I know about arithmetic on pointers from C / C++. Oh yes, I know about the Unsafe class from Sun Java too. 🙂

Go ahead, Null Ninja! Apply these tips and push that cyclomatic complexity down, down, down!



Tags:
This entry was posted on Wednesday, May 25th, 2011 at 2:55 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

9 Responses to “Java NullPointerException Ninja – 10 facts you need to know to avoid problems with null”

  1. Shrikant

    Also
    synchronized (thereGoesNull) {
    //Don’t bother, won’t reach here
    }

  2. Shrikant

    Nice collection by the way

  3. Bazzatron

    Re: Point 4

    Object a = null;
    Object b = null;
    System.out.println( (a==b)+” and “+(null==null) );

    …true and true

  4. Onkar Joshi

    @Bazzatron
    I don’t know what I was thinking of when I wrote that. That wasn’t right – probably late at night and got mixed up with some other point I was trying to make.

    Replaced it.

    Thanks for pointing it out.

  5. Onkar Joshi

    @Bazzatron

    Oh yes. I must have been thinking about SQL – http://stackoverflow.com/questions/191640/get-null-null-in-sql

  6. Tomáš Záluský

    #6 is true for Sun/Oracle JDK java compiler. For Eclipse JDT compiler it isn’t true, see this thread in Czech Java conference (sorry only Czech is available, but google translation seems to be comprehensible):
    http://translate.google.com/translate?sl=cs&tl=en&js=n&prev=_t&hl=cs&ie=UTF-8&layout=2&eotf=1&u=http%3A%2F%2Fwww.mail-archive.com%2Fkonference%40java.cz%2Fmsg11975.html

  7. Rajiv

    checking null before calling any method or accessing field is a defensive programming but required for stability of application. This site has provides good introduction and fix of NullPointerException.

  8. java67

    I agree most common cause of NPE is incorrect use of equals method. you can avoid NPE by using string literal with equals method. i.e. instead of string.equals(“code”) use “code”.equals(string)

    source: http://goo.gl/Q6BFH

  9. Meghraj Raskar

    My mobiles game not working. Look error in display null pointer