tags:

views:

180

answers:

3

There are discussion around Integer vs int in Java. The default value of the former is null while in the later it's 0. How about Boolean vs boolean?

A variable in my application can have 0/1 values. I would like to use boolean/Boolean and prefer not to use int. Can I use Boolean/boolean instead?

Thanks.

+3  A: 

yes use can use Boolean/boolean instead .

First one is Object second one is primitive type

On first one you will get more methods which will be useful

Second one is cheap considering memory expense.

Now choose your way

org.life.java
You could have phrased this as "the second will save you a lot more memory, so go for it". The useful methods on Boolean can mostly be invoked without having an instance of it.
DJClayworth
@DJClayworth edited
org.life.java
As long as you use instead Boolean.valueOf(value) of new Boolean(value), memory shouldn't be a concern.
gregcase
+2  A: 

You can use the Boolean constants - Boolean.TRUE and Boolean.FALSE instead of 0 and 1. You can create your variable as of type boolean if primitive is what you are after. This way you wont have to create new Boolean objects.

CoolBeans
A: 

Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this

boolean result = Boolean.TRUE;

or

Boolean result = true; 

Which essentially the compiler does,

Boolean result = Boolean.valueOf(true);

So, for your answer, it's YES.

The Elite Gentleman
Thanks for the hints!