As the previous answers stated, Boolean.TRUE
returns the wrapper object of the boolean value true
, so for the contexts where we need to treat boolean's like objects (for example, having an ArrayList
of booleans), we could use Boolean.TRUE
or Boolean.FALSE
As for why:
boolean boolVar = Boolean.TRUE;
is valid is because of Autoboxing and Unboxing.
In short, the Java compiler, when it sees you treating a primitive like an object, such as
List<Boolean> listOfBoolean = new ArrayList<Boolean>();
boolean someBool = true;
listOfBoolean.add(someBool);
it will automatically wrap it, or autobox it
List<Boolean> listOfBoolean = new ArrayList<Boolean>();
boolean someBool = true;
listOfBoolean.add(Boolean.valueOf(someBool));
And if it sees you treating a wrapper object, like Boolean.TRUE
, as a primitive, like:
boolean boolVar = Boolean.TRUE;
it will convert it down into a primitive, or unbox it, like if we did:
boolean boolVar = Boolean.TRUE.booleanValue();
Once upon a time, you'd have to do this by hand, but now, for better or for worse, this is mostly taken care of for you.
And if you're wondering why have Boolean.TRUE
at all, it's because there is no need to have floating around lots of Boolean objects for true
. Since a boolean can only be one of two values, it's simpler just to have them as constants rather than, for every time someone needs boxed up true
:
Boolean trueBool = new Boolean(true);