Why is “boolean val = (0 == 0 ? null : true)” causing a Java NullPointerException ?

This would be a funny interview question : why is the following Java code compiling but throwing a NullPointerException at runtime ?

boolean val = (0 == 0 ? null : true);

Since boolean is a primitive data type, it can’t be initialized with a null value. As a matter of fact, the compiler rejects the following code :

boolean val = null;

So, one would expect the conditional/ternary operator assignement to also fail at compile time, whether because null can’t be assigned to a boolean, or because null and true don’t have the same data type, which is not allowed by the ternary operator.
That’s not the case, compilation runs fine, only at runtime do you get a NullPointerException.
Why ?

I guess this comes from Java autoboxing/autounboxing feature. Since the “then” and “else” parts of the operator must have the same type, Java autoboxes true to Boolean.TRUE, and assumes null is a Boolean. Knowing that Boolean can be autounboxed to boolean, the compiler will accept the statement.

Then, at runtime, null will be autoboxed to boolean, eventually causing the NullPointerException. Et voilà !

Leave a Reply

Your email address will not be published. Required fields are marked *