Boolean with 3 States
It’s wonderful to know how we can use wrappers
& primitives
to our benefit. This was something I found while reading through Oracle Java Tutorials.
So without further due, here is the thing.
Back to Basics
Boolean by definition has 2 states or 2 values. Here is a quote about it from Wikipedia:
In computer science, the Boolean data type is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.
But when Java introduced wrapper
classes around primitive
it essentially casted them into objects
. Now since a default value for an object
is null
, these wrappers can also be null
& so is Boolean
with a big ‘B’.
Default value for an
object
isnull
, sowrappers
can benull
& so isBoolean
with a big ‘B’
The trick
This way, we can a Boolean
wrapper reference hold any of 3 states null
, true
, false
. We could use null
as a special condition if we require such.
Some code
// By default is set to null unless we do
private Boolean checked;
// By default boolean primitive will be set to false
private boolean confirmed;
// Returns null if 'checked' is not set
public Boolean isChecked() {
return this.checked;
}
// Returns false as 'confirmed' was a primitive casted into wrapper
public Boolean isConfirmed() {
return this.confirmed;
}
Caveats
We should however use this whenever required & not everywhere & condsider these facts:
- Declaring it as a wrapper needs us an additional null check before comparing its truth values
- Ojects are larger in size compared to primitives
That’s all I had for this post. Thank you.