PMD is warning me to avoid Boolean instantiation (for efficiency reasons). I have something like this
Boolean variable = new Boolean(somestringIGotRepresentingABoolean);
And I'm supposed to use this
Boolean variable = Boolean.valueOf(somestringIGotRepresentingABoolean);
Why is that better?
FALSE is an object, so they're not really comparable. If you assign false to a Boolean variable, like this: Boolean b = false; Java's auto boxing occurs to convert the primitive into an object, so the false value is lost and you end up with Boolean.
In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.
Java boolean keyword is used to declare a variable as a boolean type which represents only one of two possible values i.e. either true or false . In java, by default boolean variables are initialized with false.
Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.
The reason is that new Boolean always returns a new instance. Since Boolean instances are immutable it does not make sense to have more than 2 instances. One for false and one for true.
Try this and you will see
Boolean boolean1 = new Boolean("true");
Boolean boolean2 = new Boolean("true");
Boolean boolean3 = new Boolean("true");
System.out.println(System.identityHashCode(boolean1));
System.out.println(System.identityHashCode(boolean2));
System.out.println(System.identityHashCode(boolean3));
Boolean valueOf1 = Boolean.valueOf("true");
Boolean valueOf2 = Boolean.valueOf("true");
System.out.println(System.identityHashCode(valueOf1));
System.out.println(System.identityHashCode(valueOf2));
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