You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example: Boolean testvar = null; if (testvar == null) { ...}
What does a null Boolean mean? A null Boolean means that the variable has no reference assigned, so it is neither true nor false, it is “nothing”.
An alternative approach is to use the logical OR (||) operator. To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean.
It be that you need to test if SessionManager is null before you access it, or maybe the HoldStringId needs to be tested for null, as well as that. Nullable types can be checked using the HasValue property, and their value can be retrieved with the Value property.
If you don't like extra null checks:
if (Boolean.TRUE.equals(value)) {...}
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) { ... }
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.
Or with the power of Java 8 Optional, you also can do such trick:
Optional.ofNullable(boolValue).orElse(false)
:)
Boolean
types can be null
. You need to do a null
check as you have set it to null
.
if (bool != null && bool)
{
//DoSomething
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With