Autoboxing and Unboxing


[Page 837 (continued)]

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:

Integer iObj = new Integer(345); double num = -2.345; Double dObj = new Double(num); 


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 shown above can be accomplished with the simpler code:

Integer iObj = 345; double num = -2.345; Double dObj = num; 


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:

int m = iObj.intValue(); double x = dObj.doubleValue(); 


Java 5.0 allows the simpler:

int m = iObj; double x = dObj; 



[Page 838]

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 situation 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 in simplifying one's code:

Stack<Integer> stack = new Stack<Integer>(); for(int k = -1; k > -5; k--)     stack.push(k); while (!stack.empty())     System.out.println(Math.abs(stack.pop())); 


Note 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 description of where autoboxing and unboxing takes place and a list of some special situations where code allowing autoboxing can lead to confusion and problems.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net