Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean != false

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?

like image 625
Bart van Heukelom Avatar asked Nov 30 '10 12:11

Bart van Heukelom


People also ask

What happens if a boolean statement is false?

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.

What does != Mean in boolean?

>= : Greater than or equal to. <= : Less than or equal to. == : Equal to. != : Not equal to.

Can boolean be true or false?

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.

What is the boolean value of false?

Constant true is 1 and constant false is 0.


2 Answers

If you want to handle Boolean instances as well as primitives and be null-safe, you can use this:

if(Boolean.TRUE.equals(someBool)) 
like image 63
Michael Borgwardt Avatar answered Oct 14 '22 20:10

Michael Borgwardt


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)

like image 27
Bozho Avatar answered Oct 14 '22 19:10

Bozho