232

I have the following code:

Boolean bool = null;

try 
{
    if (bool)
    {
        //DoSomething
    }                   
} 
catch (Exception e) 
{
    System.out.println(e.getMessage());             
}

Why does my check up on the Boolean variable "bool" result in an exception? Shouldn't it just jump right past the if statement when it "sees" that it isn't true? When I remove the if statement or check up on if it's NOT null, the exception goes away.

Birdman
  • 5,244
  • 11
  • 44
  • 65
  • 4
    The answers above about object unboxing are all correct. For completeness sake, however, you could also change your code to use the primitive "boolean" instead of the object wrapper "Boolean". You should also refresh yourself on the difference between a primitive and an Object. – Marvo Jun 12 '12 at 22:34
  • Meanwhile... `if (bool == Boolean.TRUE)` evaluates false without generating an exception. Not sure if this was intentional in the case I just found. – simon.watts Apr 16 '18 at 12:03
  • 4
    @simon.watts that would be false for `bool` being `null` OR if `Boolean` was constructed explicitly (and not as reference to `Boolean.TRUE`). So not recommended; as opposed to `if (Boolean.TRUE.equals(bool))` which would work as expected, including safely handling `null` value. – StaxMan Feb 21 '19 at 01:07

8 Answers8

562

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}
Steven Byle
  • 13,149
  • 4
  • 45
  • 57
AvrDragon
  • 7,139
  • 4
  • 27
  • 42
  • 2
    @AvrDragon: does equals required ? Operator == works here since Boolean has only two values – Atul Sep 17 '14 at 13:17
  • 13
    @Atul Yes, equals is required here. Because (new Boolean(true) == new Boolean(true)) is.... false. Reason: Boolean is just an class and can have multiple instances as any other class in java. – AvrDragon Dec 02 '14 at 14:45
  • 51
    yeah, that's a shame, the constructor should be private so it's ensured that it's a twingleton... – fortran Jun 04 '15 at 19:23
  • 5
    This is exactly what Apache BooleanUtils' `BooleanUtils.isTrue( bool );` does. – nidheeshdas Aug 04 '16 at 05:12
  • 16
    There's absolutely no point in using Apache BooleanUtils over this idiom. – StaxMan Feb 21 '19 at 01:25
  • We can not really ignore null check here. Reason being if you add else block it will go to else for both null and false value. – Anurag Sharma Jun 24 '21 at 12:06
  • If I think about it a little bit: it is just a particular case of yoda notation. – AvrDragon May 13 '22 at 12:16
204

When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.

In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:

if(bool != null && bool) { ... }
K-ballo
  • 80,396
  • 20
  • 159
  • 169
109

Use the Apache BooleanUtils.

(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

Don't reinvent the wheel. Leverage what's already been built and use isTrue():

BooleanUtils.isTrue( bool );

Checks if a Boolean value is true, handling null by returning false.

If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • 86
    Reinventing the wheel doesn't seem so bad when the alternative is using an external library for something as basic as this. – Paul Manta Dec 25 '14 at 17:13
  • 5
    @PaulManta I agree if this is the only thing you'd *ever* use in the Apache Utils libraries, but the suggested idea is to "peruse" the libraries to expose yourself to other helpful functions. – Joshua Pinter Dec 26 '14 at 17:42
  • 1
    There is a performance penalty for using these libraries. So for such basic things which are part of the language, you should not use libraries. – ACV Mar 12 '15 at 12:53
  • @Vlad Like I wrote to PaulManta, I agree, if this is the **only** thing you are going to use this library for then it's not worth the performance and "bloat" hit but often times it'll expose you to other helper functions that you can use, which makes the inclusion worth the weight. – Joshua Pinter Mar 12 '15 at 13:54
  • @Josh Pinter it is not only about the weight of the inclusion, but also the overhead of calling that utility function. There is a space and time penalty for that. – ACV Mar 12 '15 at 20:09
  • 9
    *That* library is reinventing the wheel. I attempt to avoid such libraries as much as possible. – Martín Schonaker Jul 24 '15 at 15:25
  • 7
    @mschonaker If Apache BooleanUtils is reinventing the wheel, what is the _original_ wheel? The idea is to avoid creating a bunch of helper functions that mimic what's already been done in libraries such as this. I also use `toStringYesNo` from this library in all of my applications. – Joshua Pinter Jul 26 '15 at 15:25
  • Including an an entire library to get that functionality is not the right thing. – Jeffrey Blattman Feb 19 '16 at 21:21
  • 3
    Wouldn't the original wheel be `Boolean.TRUE.equals(bool)`? There are definitely some useful methods in `BooleanUtils`, but you don't need it for this. – nnnnnn Aug 01 '16 at 06:13
  • @nnnnnn Definitely don't _need_ it for this. Just another option. And an intro to Apache's utility libraries for those that are uninitiated. – Joshua Pinter Aug 03 '16 at 14:53
  • The BooleanUtils code says: `return bool.booleanValue() ? true : false;` Isn't that redundant? Is it for better readability? – David Balažic Dec 08 '16 at 12:15
  • Coming back to my answer 6 years later and I still like this. **But** be careful with `BooleanUtils.isFalse( bool )`. When `bool` is `null` it will return `false`, which may not be what you were expecting. – Joshua Pinter Jun 12 '20 at 01:50
  • How absurd is the type system in java when we need a library to tell if a boolean is false... – Adam Hughes Apr 18 '22 at 15:51
36

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

provisota
  • 1,390
  • 1
  • 14
  • 14
16

Boolean types can be null. You need to do a null check as you have set it to null.

if (bool != null && bool)
{
  //DoSomething
}                   
dimo414
  • 47,227
  • 18
  • 148
  • 244
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
2

if (bool) will be compiled to if (bool.booleanValue()) aka unboxing and that would throw a NullPointerException if bool is null.

Other solutions for nullable boxed Boolean evaluation:

false is used as the default for the null-case here.

bjmi
  • 497
  • 3
  • 12
1

as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.

RicardoE
  • 1,665
  • 6
  • 24
  • 42
  • 2
    If it were just that, the `catch` block would handle the NullPointerException. The problem here is that the OP attempts to unbox a null-reference into a primitive. – Mike Adler Jun 12 '12 at 21:54
  • 1
    *"you will always"* - Not always, except for the sample, simplified code that doesn't do anything in between initialising the variable to `null` and then testing it. Presumably real code wouldn't be that simple or the entire `if` test could be removed. – nnnnnn Aug 01 '16 at 06:19
0

Objects.equals()

There is nothing wrong with the accepted answer by K-ballo. If you prefer a single simple condition and like me you don’t like Yoda conditions, since java 1.7 the answer is

    if (Objects.equals(bool, true)) {

or if at the same time you prefer to be really explicit

    if (Objects.equals(bool, Boolean.TRUE)) {

Or better: avoid the issue

It’s not recommended to use Boolean objects thereby allowing a Boolean reference to be null in the first place. The risk of a NullPointerException like the one you saw is too great. If you need a kind of tri-state logic, it’s better to define an enum with three values. For example

enum MyTristateBoolean { FALSE, DONT_KNOW, TRUE }

Now we don’t need null at all. The middle constant should probably be named UNKNOWN, UNDEFINED, NOT_EXISTING or something else depending on your exact situation. You may even name it NULL if appropriate. Now depending on taste your comparison becomes one of the following two.

    if (myBool.equals(MyTristateBoolean.TRUE)) {

    if (myBool == MyTristateBoolean.TRUE) {

The latter works since the compiler guarantees that you will only have one instance of each enum constant. As most of you know == doesn’t work for comparing objects of non-enum type for equality.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161