Unboxing is the opposite of boxing. Unboxing is the conversion of a wrapper object to their corresponding primitive value the wrapper stores.
Several object-oriented languages, such as Java, differentiate between primitive types, such as int
, with an object reference type, such as String
. Java provides eight primitive values, commonly the int, long, double, boolean, char
, and sometimes the byte, short
and float
. Primitives are the simplest data types, their type names are usually keywords, and several operations, such as inequality and arithmetic operators work only on primitive data types.
However, in some cases such as polymorphism and converting an Object to a Primitive and back, sometimes you may need to use a wrapper class, a special class whose object contains only one field, its corresponding primitive values (as well as certain methods). The names of the primitive type's corresponding wrapper class can be distinguished by the name of the primitive by beginning with an uppercase letter, and being written out in full.
These wrapper classes have a special capability called unboxing, where the compiler automatically converts the wrapper Object to its corresponding primitive, and allows performing operations which are otherwise restricted to the primitives, such as using inequality symbols <, <=, >, >=
, or passing a primitive value where it otherwise requires an Object.
Java Examples:
Using relational inequality symbols <, <=, >=, >
(operator ==
and !=
are always for reference equality or inequality for any Object respectively, no unboxing).
Integer a = 15;
Integer b = 0;
Double x = 7.5;
Double y = 15.000000000000000000000000001; // Decimal part discarded
Character ch = 'A';
/* Comparing these wrappers using inequality symbols involve unboxing. */
/* The compiler converts these Objects to its corresponding primitives, */
/* before testing inequality. */
System.out.println(x + " < " + a + " is " + (x < a));
System.out.println(x + " < " + b + " is " + (x < b));
System.out.println(a + " > " + b + " is " + (a > b));
System.out.println(ch + " <= " + 65 + " is " + (ch <= 64)); // 'A' has ASCII code 65
System.out.println(ch + " <= " + 65 + " is " + (ch <= 65));
System.out.println(a + " >= " + b + " is " + (a >= b));
Adding an integer value as an int literal to an ArrayList of Integers.
ArrayList<Integer> vector = new ArrayList<Integer>();
vector.add(1); // int literal '1' is boxed to an Integer
// The returned value, otherwise an Integer, unboxed to int with value 1
int n = vector.get(0);