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"?
In Java, the boolean keyword is a primitive data type. It is used to store only two possible values, either true or false. It specifies 1-bit of information and its "size" can't be defined precisely. The boolean keyword is used with variables and methods.
A Boolean value represents a truth value; that is, TRUE or FALSE. A Boolean expression or predicate can result in a value of unknown, which is represented by the null value.
To display Boolean type, firstly take two variables and declare them as boolean. val1 = true; Now, use if statement to check and display the Boolean true value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With