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?
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.
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.
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