In Java, you would usually say that
if(someBool != false)
is the same as
if(someBool)
But what if someBool
is not of type boolean
but Boolean
, and its value is null
?
Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return false.
>= : Greater than or equal to. <= : Less than or equal to. == : Equal to. != : Not equal to.
A Boolean variable has only two possible values: true or false. It is common to use Booleans with control statements to determine the flow of a program.
Constant true is 1 and constant false is 0.
If you want to handle Boolean
instances as well as primitives and be null-safe, you can use this:
if(Boolean.TRUE.equals(someBool))
It will throw a NullPointerException
(autounboxing of null
throws NPE).
But that only means that you must not allow a null
value. Either use a default, or don't use autounboxing and make a non-null check. Because using a null
value of a boolean means you have 3, not 2 values. (Better ways of handling it were proposed by Michael and Tobiask)
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