Java Reference
In-Depth Information
If you try to use the preceding example in a program, your program
won't compile. The
parseInt()
method is designed to fail with a
NumberFormatException
error if the argument to the method is not
a valid numeric value. To deal with errors of this kind, you must
use special error-handling statements, which are introduced during
Day 7, “Exceptions, Assertions, and Threads.”
CAUTION
Working with primitive types and objects that represent the same values is made easier
through autoboxing and unboxing, an automatic conversion process.
Autoboxing
automatically converts a primitive type to an object, and
unboxing
converts
in the other direction.
If you write a statement that uses an object where a primitive type is expected, or vice
versa, the value will be converted so that the statement executes successfully.
3
This is a marked departure from most earlier versions of the language.
As a demonstration, the following statements can't be compiled in Java 2 version 1.4:
Float f1 = new Float(12.5F);
Float f2 = new Float(27.2F);
System.out.println(“Lower number: “ + Math.min(f1, f2));
When you attempt to compile a class containing these statements, the compiler stops
with an error message stating that the
Math.min()
method requires two
float
primitive
values as arguments, rather than
Float
objects.
The statements compile successfully in Java 6. The
Float
objects are unboxed into prim-
itive values automatically when the
Math.min()
method is called.
Unboxing an object works only if the object has a value. If no con-
structor has been called to set up the object, compilation fails
with a
NullPointerException
error.
CAUTION