CHAPTER 21

image

Boxing and Unboxing

Placing a primitive variable in an object is known as boxing. This allows the primitive to be used where objects are required. For this purpose Java provides wrapper classes for each primitive – namely: Byte, Short, Integer, Long, Float, Double, Character and Boolean. An Integer object, for example, can hold a variable of the type int.

int iPrimitive = 5;
Integer iWrapper = new Integer(iPrimitive); // boxing

The opposite of boxing is unboxing. This converts the object type back into its primitive type.

iPrimitive = iWrapper.intValue(); // unboxing

The wrapper classes belong to the java.lang package, which is always imported. In contrast to primitives, wrapper objects are immutable (unchangeable). To change their value, a new instance must be created. Another difference between primitives and wrapper objects is how they are checked for equality. Primitives use the equal to operator (==), whereas objects of any type use the equals method, extending from Object. Also bear in mind that objects can be set to null whereas primitives cannot.

Autoboxing and autounboxing

Java 5 introduced autoboxing and autounboxing. These features allow for automatic conversion between primitives and their wrapper objects.

Integer iWrapper = iPrimitive; // autoboxing
iPrimitive = iWrapper;         // autounboxing

Note that this is only syntactic sugar designed to make the code easier to read. The compiler will add the necessary code to box and unbox the primitives for you – using the valueOf and intValue methods.

Integer iWrapper = Integer.valueOf(iPrimitive);
iPrimitive = iWrapper.intValue()

Primitive and wrapper guideline

Primitive types should be used when there is no need for objects. This is because primitives are generally faster and more memory efficient than objects. Conversely, wrappers are useful when numerical values are needed, but objects are required. For example, to store numerical values in a collection class, such as ArrayList, the wrapper classes are needed.

java.util.ArrayList a = new java.util.ArrayList();
a.add(Integer.valueOf(5)); // boxing
a.add(10);                 // autoboxing

Bear in mind that conversions between primitives and wrapper objects should be kept low if speed is important. There is an inherit performance penalty associated with any boxing and unboxing operation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.247