Have you ever written this line of code?
According to FindBugs (and rightly so) should not instantiate Boolean objects in Java as we did above. Instead we must use the creational method provided to us.
This is better for performance. Since we can have only two Boolen values, either true or false, the JVM can cache both these objects, and we can reuse them across our application by using the above creational method, instead creating new Boolean objects every time we need them.
Discuss this post in the learning forum.
Boolean b = new Boolean(false);
According to FindBugs (and rightly so) should not instantiate Boolean objects in Java as we did above. Instead we must use the creational method provided to us.
Boolean b = Boolean.valueOf(false);
This is better for performance. Since we can have only two Boolen values, either true or false, the JVM can cache both these objects, and we can reuse them across our application by using the above creational method, instead creating new Boolean objects every time we need them.
Discuss this post in the learning forum.
Comments
You are right, and in a way
Boolean.valueOf(false)
does use the constant under the hoods.
One reason why we our code (maybe a method) gets a boolean in a parameter and had to create a Boolean object from it.
In such a scenario if we directly use the constant we will have to write an if...else stament:
someMethod(boolean b) {
Boolean bObj;
if(b)
bObj = Boolean.TRUE;
else
bObj = Boolean.FALSE;
}
However, we can eliminate the if... else by simply using
Boolean.valueOf(b);
which will lookup the constant under the hoods.
if()