Search code examples
javabooleanwrapperunboxing

Passing Boolean to method that expects boolean


I am passing a Boolean value to a method that has a boolean parameter.

When my value is null what happens? Will it assign a default value, like false to the argument in a method or will it cause any problems?


Solution

  • 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);