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.
This question is related to
java
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) { ... }
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.
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:
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.
Boolean
types can be null
. You need to do a null
check as you have set it to null
.
if (bool != null && bool)
{
//DoSomething
}
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
Source: Stackoverflow.com