dingalapadum
dingalapadum

Reputation: 2177

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?

Upvotes: 10

Views: 16145

Answers (2)

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4582

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.

Upvotes: 3

Jiri Tousek
Jiri Tousek

Reputation: 12440

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.

Upvotes: 5

Related Questions