11.5. Case Study - The Rational Class

 
[Page 362 ( continued )]

10.6. Automatic Conversion Between Primitive Types and Wrapper Class Types

JDK 1.5 allows primitive types and wrapper classes to be converted automatically. For example, the following statement in (a) can be simplified as in (b) due to autoboxing:

Converting a primitive value to a wrapper object is called boxing . The reverse conversion is called unboxing . The JDK 1.5 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. Consider the following example:

 1 Integer[] intArray = {   1   ,   2   ,   3   }; 2 System.out.println(intArray[     ] + intArray[   1   ] + intArray[   2   ]); 


[Page 363]

In line 1, primitive values 1, 2, and 3 are automatically boxed into objects new Integer(1) , new Integer(2) , and new Integer(3) . In line 2, objects intArray[0] , intArray[1] , and intArray[2] are automatically converted into int values that are added together.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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