© Mikael Olsson 2018
Mikael OlssonJava Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-3441-9_21

21. Boxing and Unboxing

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, Finland
 

Placing a primitive variable in an object is known as boxing. Boxing allows the primitive to be used where objects are required. For this purpose, Java provides wrapper classes to implement boxing for each primitive type —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, naturally, unboxing, which 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. When using wrapper objects, keep in mind that the equal to operator (==) checks whether both references refer to the same object, whereas the equals method is used to compare the values that the objects represent:

Integer x = new Integer(1000);
Integer y = new Integer(1000);
boolean b = (x == y);    // false
        b = x.equals(y); // true

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’s no need for objects. That’s 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’s 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.188.218.226