Throw a null-pointer exception
Java

Let's calculate the absolute value of a number. Java has Math.abs for this purpose, however the number we're using could be null sometimes. So we need a helper method to deal with that case:

public class NPE {
    public static Integer abs(final Integer x) {
        return x == null ? x : Math.abs(x);
    }

    public static void main(final String... args) {
        System.out.println(abs(null));
    }
}


If x is null, return null, else use Math.abs().
The code is very simple and clear, and should work fine... right?

By the way, using this line instead:

return x == null ? null : Math.abs(x);


works correctly. I thought about making this a spoiler, but.. I think it's just as puzzling :)

Ok, an explanation:


   First, Math.abs does not take an Integer, but an int (there are also overloaded methods for other numeric types) and also returns an int. In java, int is a primitive type (and can not be null) and Integer is its corresponding class (and can be null). Since java version 5, a conversion between int and Integer is performed automatically when needed. So Math.abs can take x, automatically converted to int, and return an int.

 Now the weird part: when the ternary operator (?:) has to deal with 2 expressions where one has a primitive type and the other one has its corresponding class (such as int and Integer), one would expect that java would convert the primitive to the class (aka "boxing"), especially when the type it needs (here for returning from the method) is the reference (class) type, and the first expression is also of the reference type. But java does exactly the opposite: it converts the reference type to the primitive type (aka "unboxing"). So in our case, it would try to convert x to int, but int can not be null, thus it throws a NPE.

 If you compile this code using Eclipse, you will actually get a warning: "Null pointer access: This expression of type Integer is null but requires auto-unboxing"

 Also see:
 https://stackoverflow.com/questions/7811608/java-npe-in-ternary-operator-with-autoboxing
 https://stackoverflow.com/questions/12763983/nullpointerexception-through-auto-boxing-behavior-of-java-ternary-operator