Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean.FALSE or new Boolean(false)?

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?

like image 880
dingalapadum Avatar asked Oct 08 '15 11:10

dingalapadum


People also ask

What is new Boolean?

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.

What is a false Boolean?

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.

What is new Boolean in Java?

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 .

What is the Boolean value of false?

Boolean values and operations Constant true is 1 and constant false is 0.


2 Answers

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.

like image 100
Jiri Tousek Avatar answered Sep 24 '22 09:09

Jiri Tousek


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.

like image 26
Gaurav Jeswani Avatar answered Sep 25 '22 09:09

Gaurav Jeswani