When should I use Boolean instead of boolean?

Generally speaking, the wrapper classes are used in cases where an object is required or strongly preferred. Outside of these situations, it's better to use the primitive types, since they have lower overhead, you can use ==, etc. There are two and a half major situations where this is frequently seen:

  • Collections. This is now a subset of the next case, but even before Java 5 the Collections classes only supported objects as keys and values, and this hasn't changed.
  • Generics. Generic types can only work with objects, not primitives, and so if you're using "boolean" as a type parameter, it has to be the wrapper class. For example, if you're using a Future, you have to use a Boolean instead of a boolean. (HT @user949300)
  • ORM. JPA and other ORM systems technically can use primitive fields, but it's customary to use the wrapper classes, since the overhead is high enough that that doesn't really matter anyway, and the wrapper classes can represent a NULL value that might be present in the database. It's usually still better to forbid nulls and use a primitive for booleans, though, since semantically a default is usually better than "undefined".

Since boolean values are restricted to either true or false, it's uncommon to see them used in Collections or Generics; generally speaking, if you'd have a boolean as a value, you'll just use Collection#contains instead.


IMHO the primitive is better.

Always favor primitives over wrappers. Wherever I am able to use primitives, I go for them because at run time, if we use wrappers, boxing conversions and unboxing conversions happen, and obviously that takes more time. If you use the primitive there, you save that time.

And as usual it depends on your requirements whether you need a Object (which can be null) or you can use a primitive (which cannot be null) in your situation.

For example: Assume you are dealing with collection's then you have no option's,You have to use wrappers :).

Tags:

Java