ChatGPT解决这个技术问题 Extra ChatGPT

Check if null Boolean is true results in exception

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.

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.
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 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.

S
Steven Byle

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

@AvrDragon: does equals required ? Operator == works here since Boolean has only two values
@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.
yeah, that's a shame, the constructor should be private so it's ensured that it's a twingleton...
This is exactly what Apache BooleanUtils' BooleanUtils.isTrue( bool ); does.
There's absolutely no point in using Apache BooleanUtils over this idiom.
K
K-ballo

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) { ... }

Technically a Boolean can be any number of true instances, not just Boolean.TRUE. For example new Boolean(true).
I struggle to understand why if (myBoolean) (where myBoolean is Boolean) does not raise a compiler error or at least a warning. This is a gotcha for sure.
@JoshM. This is because Java does Boxing and Unboxing of wrappers: docs.oracle.com/javase/tutorial/java/data/autoboxing.html
@Vinicius sure, but the compiler should either do the null for us in this case, out through a compiler warning at least.
J
Joshua Pinter

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.


Reinventing the wheel doesn't seem so bad when the alternative is using an external library for something as basic as this.
@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.
That library is reinventing the wheel. I attempt to avoid such libraries as much as possible.
@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.
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.
p
provisota

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

Optional.ofNullable(boolValue).orElse(false)

:)


This answer should get more recognition, but that's just my opinion.
d
dimo414

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

if (bool != null && bool)
{
  //DoSomething
}                   

O
Orlan

Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.

The wrapper classes in the Java API serve two primary purposes:

To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

http://en.wikipedia.org/wiki/Primitive_wrapper_class


R
RicardoE

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.


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.
"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.
b
bjmi

if (bool) will be compiled as if (bool.booleanValue()) and that would throw a NPE if bool is null.

Other solutions for nullable boxed Boolean evaluation:

JDK 9+ import static java.util.Objects.requireNonNullElse; if (requireNonNullElse(bool, false)) { // DoSomething

Google Guava 18+ import static com.google.common.base.MoreObjects.firstNonNull; if (firstNonNull(bool, false)) { // DoSomething

false is used for the null-case here.


O
Ole V.V.

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.