PS: I understand the difference between "true" and true.
Edit: I also understand that Boolean.TRUE is a wrapper for the primitive true, my question then is - why does the primitive boolean accept Boolean.TRUE as a value? For instance,
boolean boolVar = Boolean.TRUE;
seems to be a valid statement.
What exactly difference between true() and true. true() is a function. true is boolean value. But we can use both anywhere and it works.
The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Example: Boolean. parseBoolean("True") returns true . Example: Boolean.
In Java, a boolean is a literal true or false , while Boolean is an object wrapper for a boolean . There is seldom a reason to use a Boolean over a boolean except in cases when an object reference is required, such as in a List .
, ==. These logical boolean operators help in specifying the condition that will have the two return values – “true” or “false”.
The reason
boolean boolVar = Boolean.TRUE;
works is because of autounboxing, a Java 5 feature that allows a wrapper object to be converted to its primitive equivalent automatically when needed. The opposite, autoboxing, is also possible:
Boolean boolVar = true;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With