Boolean.FALSE or new Boolean(false)?

12,363

Solution 1

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.

Solution 2

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.

Share:
12,363
dingalapadum
Author by

dingalapadum

I want to keep an air of mystery about me. (and still get a badge ;))

Updated on September 15, 2022

Comments

  • dingalapadum
    dingalapadum over 1 year

    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?