Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of initializing a Boolean

Tags:

java

How a Boolean instance has to be initialized?

Is it

Boolean b = null;

or

Boolean b = new Boolean(null);

Which one is the correct coding practice?

like image 627
Abichellam Avatar asked Mar 04 '26 11:03

Abichellam


2 Answers

The first one is correct if you want a null Boolean.

Personally I don't like having null values and prefer to use boolean, which cannot be null and is false by default.

In order to understand what the second statement does you need to understand about Java primitive wrappers. A Boolean is simply an object wrapper around a boolean; when you declare directly:

Boolean b = false;

There is some autoboxing going on and this is essentially equivalent to writing

Boolean b = Boolean.FALSE;

If you declare a new Boolean then you create a new and separate Boolean object rather than allowing the compiler to (possibly) reuse the existing reference.

It rarely (if ever) makes sense to use the constructor of the primitive wrapper types.

like image 86
Boris the Spider Avatar answered Mar 06 '26 01:03

Boris the Spider


There is absolutely no need to create a new object for Boolean. This is what javadoc says

Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.

like image 43
Prasad Kharkar Avatar answered Mar 06 '26 00:03

Prasad Kharkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!