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?
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?
Copyright © 2021 Jogjafile Inc.
Unboxing
When you call a method that wants a
booleanbut give it aBoolean, Java has to unbox the value. This happens automatically and implicitly.Therefore, during compilation, Java replaces your call
by
This process is explained in detail in JLS, chapter 5.1.8. Unboxing Conversion:
Unboxing
nullNow, when
valueisnull, this statement obviously leads to aNullPointerExceptionat 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
falseinsteadIn case you want the method to receive
falseas fallback value, you have to code this explicitly yourself. For example by: