Boolean != false

47,326

Solution 1

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)

Solution 2

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

if(Boolean.TRUE.equals(someBool))

Solution 3

Use ApacheCommons BooleanUtils.isTrue() or .isFalse()

Solution 4

If someBool is Boolean

if (someBull != null && someBull) {
  //Yeah, true.
}

Since Boolean can be null make sure you avoid NullPointerException by checking for not null.

Solution 5

I did a little test:

    Boolean o = null;
    try {
        System.out.println(o ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        System.out.println((o != false) ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }

The output is surprising:

java.lang.NullPointerException
    at btest.main(btest.java:10)
java.lang.NullPointerException
    at btest.main(btest.java:15)

The first NPE is to be expected, because o will be autounboxed (and that fails because it's null). The second happens for the same reason, but it doesn't feel natural. Anyway, the solution is to do:

System.out.println(!Boolean.FALSE.equals(o) ? "yes" : "no");
Share:
47,326
Bart van Heukelom
Author by

Bart van Heukelom

Professional software developer, online games, full stack but mostly backend. Electronics tinkerer. Maker. Freelance. See LinkedIn for more details. My UUID is 96940759-b98b-4673-b573-6aa6e38272c0

Updated on April 28, 2020

Comments

  • Bart van Heukelom
    Bart van Heukelom about 4 years

    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?