java.lang.NullPointerException with boolean

null cannot be auto-unboxed to a primitive boolean value, which is what happens when you try to compare it with true. In

param == true

The type of true is boolean, therefore the left-hand operand must also be a boolean. You are passing in a Boolean, which is an object, but can be auto-unboxed to boolean.

Therefore this is equivalent to

param.booleanValue() == true

Clearly, if param is null, the above throws NullPointerException.

To avoid the hidden pitfalls of auto-unboxing, you could instead work with the Boolean objects:

if (Boolean.TRUE.equals(param))
  return "a";
if (Boolean.FALSE.equals(param))
  return "b";
return "c";

Leave a Comment