Subtle number boxing error in Java leads to Exceptions

By Steve Claridge on 2015-04-15.

Cast your eye over this innocent-looking code snippet and see if you can spot the potential null pointer exception. I guess the title of this post is kinda giving it away.

    public long square( long l )
    {
        return l * l;
    }     public Long numStuff( Long l )
    {
        l += 10;
        return square( l );
    }

Some calling code will call numStuff(), which in turn calls square() and returns the result. Pretty simple, but a null pointer can occur here because I have mixed the use of Long and long and forced Java to box/unbox them when passing the value between the numStuff() and square() methods as numStuff() holds a Long and square() expects a long .

If I called numStuff() like this then all is good in the world

numStuff( new Long( 7 ) );

But if for some reason my Long object was a null reference and numStuff() was called as below then we have a problem.

numStuff( null );

This will compile because the Long object can be null, but when numStuff() tries to call square() Java tries to autobox the null object into a primitive long type and throws a null pointer exception.

Be careful of mixing primitives and their auto-boxed equivalents

Be careful when mixing primitives and Objects, auto-boxing occurs whenever one is converted to the other, which can be difficult to spot, in a method parameter for example, and give you a debugging headache.