When should null values of Boolean be used?
Use boolean
rather than Boolean
every time you can. This will avoid many NullPointerException
s and make your code more robust.
Boolean
is useful, for example
- to store booleans in a collection (List, Map, etc.)
- to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
- each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like
MessageFormat.format()
.
There are three quick reasons:
- to represent Database boolean values, which may be
true
,false
ornull
- to represent XML Schema's
xsd:boolean
values declared withxsd:nillable="true"
- to be able to use generic types:
List<Boolean>
- you can't useList<boolean>
I almost never use Boolean
because its semantics are vague and obscure. Basically you have 3-state logic: true, false or unknown. Sometimes it is useful to use it when e.g. you gave user a choice between two values and the user didn't answer at all and you really want to know that information (think: NULLable database column).
I see no reason to convert from boolean
to Boolean
as it introduces extra memory overhead, NPE possibility and less typing. Typically I use awkward BooleanUtils.isTrue()
to make my life a little bit easier with Boolean
.
The only reason for the existence of Boolean
is the ability to have collections of Boolean
type (generics do not allow boolean
, as well as all other primitives).
Wow, what on earth? Is it just me or are all these answers wrong or at least misleading?
The Boolean class is a wrapper around the boolean primitive type. The use of this wrapper is to be able to pass a boolean in a method that accepts an object or generic. Ie vector.
A Boolean object can NEVER have a value of null. If your reference to a Boolean is null, it simply means that your Boolean was never created.
You might find this useful: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Boolean.java
A null Boolean reference should only be used to trigger similar logic to which you have any other null reference. Using it for three state logic is clumsy.
EDIT: notice, that Boolean a = true;
is a misleading statement. This really equals something closer to Boolean a = new Boolean(true);
Please see autoboxing here: http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Autoboxing
Perhaps this is where much of the confusion comes from.
EDIT2: Please read comments below. If anyone has an idea of how to restructure my answer to incorporate this, please do so.