Documentation for the constructor new Boolean(boolean value)
in Java states:
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 so, why is this constructor public and not deprecated? Is there ever a good reason to use this constructor instead of Boolean.valueOf()
?
public Boolean(String s) Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Otherwise, allocate a Boolean object representing the value false . Examples: new Boolean("True") produces a Boolean object that represents true.
Constructors in Boolean Class This constructor creates the Boolean object that passes a Boolean value. Boolean b = new Boolean (String s); This constructor helps in creating a Boolean object, that creates the value true if the string argument is not null and is equal.
An object of type Boolean contains a single field whose type is boolean . In addition, this class provides many methods for converting a boolean to a String and a String to a boolean , as well as other constants and methods useful when dealing with a boolean .
Java Boolean equals() methodThe equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.
valueOf()
only got added in Java 1.4, so it would appear that the constructors exist for backwards compatibility.
This ticket explains the reasons for not deprecating the constructors:
Due to the disruption deprecating an API can have, currently an API has to be "actively hazardous" to be deprecated, like Thread.stop. While the use this constructor is certainly ill-advised, it doesn't rise (or sink) to the standard of hazardousness to be deprecated in the JDK. In the future we may add a "denigration" facility to mark API elements that aren't quite so bad that they should be deprecated, but shouldn't be used in most cases. This constructor would be a good candidate for denigration.
I can't think of a realistic scenario where using Boolean
constructors would be the best way to do something useful.
Usually, you will want to use valueOf(boolean)
or even the Boolean.TRUE
/ Boolean.FALSE
constants directly.
But think of a scenario where you want to use a private Boolean
variable as a monitor for synchronizing threads. There you will need to make sure you use your own instance and have full control of it.
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