I saw in the source of the Boolean class the following:
public static final Boolean FALSE = new Boolean(false);
Hence, if I understand correctly the field FALSE
in the Boolean
class is a Boolean
itself which has its boolean
field set to false
.
Now I wonder if the following two statements are truly equivalent.
Boolean myBool = new Boolean(false);
and
Boolean myBool = Boolean.FALSE;
I would assume that in the first case a new Boolean object is constructed and the myBool reference points to it, whereas in the second case we actually make a copy of the reference to the Boolean.FALSE object - is this correct?
And if so what does this difference really mean?
Last but not least the actual question: Which of the two options should I prefer and why?
The Complete Full-Stack JavaScript Course! The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. The new Boolean() is used to create a new object.
Definition: A Boolean is a type of data that has only two possible values: true or false. You can think of a boolean like the answer to a yes or no question. If the answer is yes, the Boolean value is true. If the answer is no, the boolean value is false.
new Boolean("True") produces a Boolean object that represents true . new Boolean("yes") produces a Boolean object that represents false . Parameters: s - the string to be converted to a Boolean .
Boolean values and operations Constant true is 1 and constant false is 0.
The difference:
Boolean.FALSE == Boolean.FALSE
(boolean) true
new Boolean(false) == new Boolean(false)
(boolean) false
Use
Boolean myBool = false;
and let autoboxing handle it.
You should use Boolean.FALSE rather than creating a new Object on heap, because it's unnecessary. We should use this static final Object it the memory and even it's faster to access this.
And yes you are correct that :
first case a new Boolean object is constructed and the myBool reference points to it
But in second case we just point to existing object.
And your another question while we have Boolean.FALSE why we have the option to new Boolean(false) the reason is that it's a constructor. Suppose that you have a primitive boolean variable x and you don't know it's value whether it's true or false and you want a corresponding Boolean Object, than this constructor will be used to pass that primitive boolean variable x to get Boolean object.
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