Datasheet

Valid Contexts for Boxing and Unboxing Conversions
Because the boxing and unboxing operations are conversions, they happen automatically with no spe-
cific instruction by the programmer (unlike casting, which is an explicit operation). There are several
contexts in which boxing and unboxing conversions can happen.
Assignments
An assignment conversion happens when the value of an expression is assigned to a variable. When the
type of the expression does not match the type of the variable, and there is no risk of data loss, the con-
version happens automatically. The precedence of conversions that happen is the identity conversion, a
widening primitive conversion, a widening reference conversion, and then the new boxing (or unbox-
ing) conversion. If none of these conversions are valid, the compiler issues an error.
Method Invocations
When a method call is made, and the argument types don’t match precisely with those passed in, several
conversions are possible. Collectively, these conversions are known as method invocation conversions.
Each parameter that does not match precisely in type to the corresponding parameter in the method sig-
nature might be subject to a conversion. The possible conversions are the identity conversion, a widen-
ing primitive conversion, a widening reference conversion, and then the new boxing (or unboxing)
conversion.
The most specific method must be chosen anytime more than one method matches a particular method
call. The rules to match the most specific method change slightly with the addition of boxing conver-
sions. If all the standard checks for resolving method ambiguity fail, the boxing/unboxing conversion
won’t be used to resolve ambiguity. Therefore, by the time checks are performed for boxing conversions,
the method invocation is deemed ambiguous and fails.
Combining boxing with generics allows you to write the following code:
import java.util.*;
public class BoxingGenericsExample {
public static void main(String args[])
{
HashMap<String,Integer> hm = new HashMap<String,Integer>();
hm.put(“speed”, 20);
}
}
The primitive integer 20 is automatically converted to an Integer and then placed into the HashMap
under the specified key.
Static Imports
Importing static data is introduced into the language to simplify using static attributes and methods.
After importing static information, the methods/attributes can then be used without the need to qualify
the method or attribute with its class name. For example, by importing the static members of the
Math
class, you can write abs or sqrt instead of Math.abs and Math.sqrt.
21
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 21