26. Java Autoboxing and Enumeration

26.1. Autoboxing and Unboxing

 

Autoboxing refers to the automatic storing of a value of primitive type into an object of the corresponding wrapper class. Before autoboxing, it was necessary to explicitly box values into wrapper class objects with code like:

,,

 

 

J

Java 5.0 automatically creates a wrapper class object from a value of primitive type in many situations where a wrapper class object is expected. The assignments above can be accomplished with the simpler code:

,,

 

 

J

There is a corresponding feature in Java 5.0 which automatically performs the unboxing of primitive values from wrapper class objects. Instead of the explicit unboxing in:

,,

 

J

 

831

 

Java 5.0 allows the simpler:

,,

 

J

Java 5.0 provides autoboxing of primitive values and automatic unboxing of wrapper class objects in expressions or in arguments of methods, where such a conversion is needed to complete a computation. Beginning programmers are unlikely to encounter many problems that require such conversions. One situa- tion which often requires boxing and unboxing are applications that involve data structures. The generic type data structures of Chapter 16 must store objects but the data to be stored might be represented as values of a primitive type. The code segment below should give you some idea of the type of situation where autoboxing and unboxing can be a genuine help simplifying one’s code:

,,

 

 

 

J

Notice that the stack.push(k) method is expecting an Integer object so the int value stored in k will be autoboxed into such an object before the method is executed. Also note that the Math.abs() method in the last line of the code fragment is expecting a value of primitive type so the Integer value returned by stack.pop() must be automatically unboxed before the Math.abs() method can be applied.

Sun’s online Java 5.0 documentation can be consulted for a more precise de- scription of where autoboxing and unboxing takes place and a list of some special situations where code allowing autoboxing can lead to confusion and problems.