Bloch points out that Java has a number of primitive types such as
booleanand each of these types has a corresponding reference type:
Boolean. These are the boxed primitives. Auto-boxing and auto-unboxing was introduced into the language in 1.5, so the Java programmer must now be more mindful of their use.
There are three main differences between primitive types and boxed primitives:
- Primitives have only their values, whereas boxed primitives have identities distinct form their values
- Primitive types cannot be
null, but boxed primitives can
- Primitive types are more space and time efficient than boxed-primitives
==operator with boxed primitives as, with any other reference type, it compares identity and you almost certainly want to be comparing value. If a boxed primitive is compared to a primitive with the
==operator, the primitive type is boxed and the identities compared, so care must also be taken here.
The process of boxing and unboxing, especially in a loop can serious impede performance.
Basically, boxes primitives should be avoided unless primitive types cannot be used, such as in collections or as parameterised types.