Reputation: 38063
Java boolean
allows values of true
and false
while Boolean allows true
, false
, and null
. I have started to convert my boolean
s to Boolean
s. This can cause crashes in tests such as
Boolean set = null;
...
if (set) ...
while the test
if (set != null && set) ...
seems contrived and error-prone.
When, if ever, is it useful to use Boolean
s with null values? If never, then what are the main advantages of the wrapped object?
UPDATE: There has been such a lot of valuable answers that I have summarised some of it in my own answer. I am at best an intermediate in Java so I have tried to show the things that I find useful. Note that the question is "incorrectly phrased" (Boolean cannot "have a null value") but I have left it in case others have the same misconception
Upvotes: 166
Views: 176838
Reputation: 19
Boolean can be very helpful when you need three state. Like in software testing if Test is passed send true , if failed send false and if test case interrupted send null which will denote test case not executed .
Upvotes: 1
Reputation: 11
For all the good answers above, I'm just going to give a concrete example in Java servlet HttpSession
class. Hope this example helps to clarify some question you may still have.
If you need to store and retrieve values for a session, you use setAttribute
(String, Object), and getAttribute
(String, Object) method. So for a boolean value, you are forced to use the Boolean class if you want to store it in an http session.
HttpSession sess = request.getSession(false);
Boolean isAdmin = (Boolean) sess.getAttribute("admin");
if (! isAdmin) ...
The last line will cause a NullPointerException
if the attribute values is not set. (which is the reason led me to this post). So the 3 logic state is here to stay, whether you prefer to use it or not.
Upvotes: 1
Reputation: 691865
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
MessageFormat.format()
.Upvotes: 256
Reputation: 21
In a strict definition of a boolean element, there are only two values. In a perfect world, that would be true. In the real world, the element may be missing or unknown. Typically, this involves user input. In a screen based system, it could be forced by an edit. In a batch world using either a database or XML input, the element could easily be missing.
So, in the non-perfect world we live in, the Boolean object is great in that it can represent the missing or unknown state as null. After all, computers just model the real world an should account for all possible states and handle them with throwing exceptions (mostly since there are use cases where throwing the exception would be the correct response).
In my case, the Boolean object was the perfect answer since the input XML sometimes had the element missing and I could still get a value, assign it to a Boolean and then check for a null before trying to use a true or false test with it.
Just my 2 cents.
Upvotes: 1
Reputation: 340803
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).
Upvotes: 59
Reputation: 38063
ANSWER TO OWN QUESTION: I thought it would be useful to answer my own question as I have learnt a lot from the answers. This answer is intended to help those - like me - who do not have a complete understanding of the issues. If I use incorrect language please correct me.
true
and false
. It is the absence of a pointer to objects. Therefore to think that Boolean is 3-valued is fundamentally wrongThe syntax for Boolean is abbreviated and conceals the fact that the reference points to Objects:
Boolean a = true;
conceals the fact that true
is an object. Other equivalent assignments might be:
Boolean a = Boolean.TRUE;
or
Boolean a = new Boolean(true);
The abbreviated syntax
if (a) ...
is different from most other assignments and conceals the fact that a might be an object reference or a primitive. If an object it is necessary to test for null
to avoid NPE. For me it is psychologically easier to remember this if there is an equality test:
if (a == true) ...
where we might be prompted to test for null. So the shortened form is only safe when a
is a primitive.
For myself I now have the recommendations:
Boolean
from a method as it could be null
. Only return boolean
.Boolean
for wrapping elements in containers, or arguments to methods where objects are requiredUpvotes: 11
Reputation: 29
There are many uses for the **null** value in the Boolean wrapper! :)
For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.
But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)
Upvotes: 1
Reputation: 3635
The best way would be to avoid booleans completely, since every boolean implies that you have a conditional statement anywhere else in your code (see http://www.antiifcampaign.com/ and this question: Can you write any algorithm without an if statement?).
However, pragmatically you have to use booleans from time to time, but, as you have already found out by yourself, dealing with Booleans is more error prone and more cumbersome. So I would suggest using booleans wherever possible. Exceptions from this might be a legacy database with nullable boolean-columns, although I would try to hide that in my mapping as well.
Upvotes: 0
Reputation: 23903
Wrapper classes for primitives can be used where objects are required, collections are a good sample.
Imagine you need for some reason store a sequence of boolean
in an ArrayList
, this can be done by boxing boolean
in Boolean
.
There is a few words about this here
From documentation:
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
Upvotes: 10
Reputation: 5135
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.
Upvotes: 33
Reputation: 2214
I suppose in some case, you should have a mechanism to distinguish a Boolean field which already set value or not.
Upvotes: 3
Reputation: 15446
Boolean
wrapper is useful when you want to whether value was assigned or not apart from true
and false
. It has the following three states:
null
Whereas boolean
has only two states:
The above difference will make it helpful in Lists of Boolean
values, which can have True
, False
or Null
.
Upvotes: 3
Reputation: 6452
Main purpose for Boolean is null value. Null value says, that property is undefined, for example take database nullable column.
If you really need to convert everyting from primitive boolean to wrapper Boolean, then you could use following to support old code:
Boolean set = Boolean.FALSE; //set to default value primitive value (false)
...
if (set) ...
Upvotes: 1
Reputation: 6237
There are three quick reasons:
true
, false
or null
xsd:boolean
values declared with xsd:nillable="true"
List<Boolean>
- you can't use List<boolean>
Upvotes: 25