Java boolean
allows values of true
and false
while Boolean allows true
, false
, and null
. I have
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.
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
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>
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
.
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 .
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()
.