Sunday, February 01, 2009

Creating Boolean Objects

Have you ever written this line of code?


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.

2 comments:

Hitesh Lad said...

Wouldn't it be better to use the constants Boolean.TRUE/Boolean.FALSE instead of creating your own? This way you don't have to keep your own reference to your true/false instances.

Parag said...

@Hitesh,

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()