A primitive type value can be automatically converted to an object using a wrapper class, and vice versa, depending on the context. Converting a primitive value to a wrapper object is called boxing. The reverse conversion is called unboxing. Java allows primitive types and wrapper classes to be converted automatically. The compiler will automatically box a primitive value that appears in a context requiring an object, and will unbox an object that appears in a context requiring a primitive value. This is called autoboxing and autounboxing. For instance, the following statement in (a) can be simplified as in (b) due to autoboxing.
Consider the following example:
1 Integer[] intArray = {1, 2, 3};
2 System.out.println(intArray[0] + intArray[1] + intArray[2]);
In line 1, the primitive values 1, 2, and 3 are automatically boxed into objects new Integer(1), new Integer(2), and new Integer(3). In line 2, the objects intArray[0], intArray[1], and intArray[2] are automatically unboxed into int values that are added together.
Top comments (0)