-6

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?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Droid
  • 45
  • 6
  • 4
    have you tried? – Stultuske Mar 10 '21 at 07:48
  • 6
    No, you will get a NullPointerException. So, don't. – Florian Schaetz Mar 10 '21 at 07:49
  • @Stultuske Yes I did, whenever we checked it worked fine but for some people its crashing. So just wanted to confirm whether this could be the issue. – Droid Mar 10 '21 at 07:53
  • You can call it like this to be null safe`yourMethod(Boolean.TRUE.equals(yourBoolean))` – Lino Mar 10 '21 at 07:53
  • 3
    Java auto-unboxes the value by calling `yourBoolean.booleanValue()` and that statement crashes with a NPE. – Zabuzard Mar 10 '21 at 07:54
  • @FlorianSchaetz thanks for the answer. Looks like we are getting the Null issue but I am wondering why is it not happening for everyone. – Droid Mar 10 '21 at 07:54
  • Are they probably not passing null values? Because if they would, they should definitely getting NPE. Could also be, that in their case the exception is somehow caught and handled differently (or do you mean they use the exact same code and get different behaviour than you?). The whole question needs a bit more detail to answer properly. – dunni Mar 10 '21 at 08:00
  • @Lino and Zabuzard thanks a lot for the help. I have handled it in code – Droid Mar 10 '21 at 08:02
  • Many IDEs have an option to generate a warning about unboxing. – greg-449 Mar 10 '21 at 13:07

1 Answers1

4

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);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82