Search code examples
javabooleanwrapperprimitive

Benefits or uses for the Boolean.booleanValue function on Java?


So, I've seen this line of code:

Boolean variable = false;
/* ..stuff.. */
if(variable.booleanValue() == false) {
/* ..more stuff..*/
}

And I've done, in a different place:

Boolean variable = false;
/* ..my stuff..*/
if(!variable) {
/* ..more of my stuff..*/
}

The question is: What is the difference/advantages of the first snippet of code over the first?

The long version is: Given I can use the Boolean variable as a primitive (boolean) one, what's the point on doing variable.booleanValue() and even comparing it to a boolean value? Doesn't this also introduces the risk (on the code impossible, but hey) of a null pointer exception if variable is not initialised?

There's any case in which is advisable using variable.booleanValue above just "variable"?


Solution

  • There is no difference between the behaviour of the two snippets.

    JLS 5.1.8:

    At run time, unboxing conversion proceeds as follows:

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

    So if (variable) {...} will execute as if (variable.booleanValue()) {...}. And because they're completely equivalent, they're both equally susceptible to NPE if variable == null.

    This means that a possible minor advantage of the explicit call to booleanValue() is that you can instantly see that variable is being dereferenced, while with variable == false it is slightly less obvious.

    Whether you add == false or a negation is a matter of taste, I prefer to avoid using the == operator to compare a boolean expression to true or false.

    But I think it's more important that you avoid Boolean altogether and use the primitive type where possible.