[Solved] Passing Boolean to method that expects boolean [closed]


Unboxing

When you call a method that wants a boolean but give it a Boolean, Java has to unbox the value. This happens automatically and implicitly.

Therefore, during compilation, Java replaces your call

foo(value);

by

foo(value.booleanValue());

This process is explained in detail in JLS, chapter 5.1.8. Unboxing Conversion:

At run time, unboxing conversion proceeds as follows:

  • If r is a reference of type Boolean, then unboxing conversion converts r into r.booleanValue()

Unboxing null

Now, when value is null, this statement obviously leads to a NullPointerException at runtime, since you are trying to call a method (booleanValue) on a variable that does not refer to any instance.

So your code crashes, it will not use any default value as fallback. Java was designed with fail-fast in mind.


Get false instead

In case you want the method to receive false as fallback value, you have to code this explicitly yourself. For example by:

foo(value == null ? false : value);

0

solved Passing Boolean to method that expects boolean [closed]