next up previous index
Next: The Iterable interface and Up: Other enhancements Previous: Other enhancements   Index


Boxing and unboxing

Primitive types and their corresponding wrapper classes can now be used interchangeably. For example the following lines of code are legitimate in Java 5:
int a = 0;
Integer b = a; //!
int c = new Integer(b); //!!
This is often referred to as automatic boxing or unboxing. If an int is passed where an Integer is expected, the compiler will automatically insert a call to the Integer constructor. Conversely, if an Integer is provided where an int is required, there will be an automatic call to the the IntValue method. Similar remarks hold for each of the other primitive types.

It follows for instance that, from the programmer's point of view, arithmetic operations are effectively defined on elements of the wrapper classes, for example:

Integer a = 1;
Integer b = 1;
Integer c = a * b;



Peter Williams 2005-06-07