Reputation: 5414
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.
Upvotes: 245
Views: 341876
Reputation: 603
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:
JDK 9+ requireNonNullElse(obj, defaultObj)
import static java.util.Objects.requireNonNullElse;
if (requireNonNullElse(bool, false)) {
// DoSomething
Google Guava 18+ firstNonNull(first, second)
import static com.google.common.base.MoreObjects.firstNonNull;
if (firstNonNull(bool, false)) {
// DoSomething
false
is used as the default for the null-case here.
Upvotes: 2
Reputation: 86276
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)) {
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.
Upvotes: 5
Reputation: 1660
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
Upvotes: 41
Reputation: 47481
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.
Upvotes: 116
Reputation: 41097
Boolean
types can be null
. You need to do a null
check as you have set it to null
.
if (bool != null && bool)
{
//DoSomething
}
Upvotes: 19
Reputation: 7479
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
Upvotes: 593
Reputation: 81349
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) { ... }
Upvotes: 211
Reputation: 1725
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.
Upvotes: 1