Java Reference
In-Depth Information
In this snippet of code, suppose you do not control the assignment of null to n. You might get a null Integer
object as a result of a method call, for example, int a = getSomeValue() , where getSomeValue() returns an Integer
object. A NullPointerException in such places may be a surprise for you. However, it will happen, because int a = n
is converted to int a = n.intValue() and n is null in this case. This surprise is the part of the advantage you get
from autoboxing/unboxing and you need to just be aware of it.
Overloaded Methods and Autoboxing/Unboxing
You have a few surprises when you call an overloaded method and want to rely on autoboxing/unboxing feature.
Suppose you have two methods in a class.
public void test(Integer iObject) {
System.out.println("Integer=" + iObject);
}
public void test(int iValue) {
System.out.println("int=" + iValue);
}
Suppose you make two calls to the test() method.
test(101);
test(new Integer(101));
Which of the following will be the output?
int=101
Integer=101
or
Integer=101
int=101
The rule for a method invocation that uses autoboxing/unboxing follows a two-step process.
If the actual argument being passed is a primitive type (as in test(10)) ,
1.
a.
Try to find a method with the primitive type argument. If there is no exact match, try
widening the primitive type to find a match.
b.
If the previous step fails, box the primitive type and try to find a match.
If the actual argument being passed is a reference type (as in test(new Integer(101)) ,
2.
a.
Try to find a method with the reference type argument. If there is match, call that
method. In this case, a match does not have to be exact. It should follow the subtype
and super type assignment rule.
b.
If the previous step fails, unbox the reference type to the corresponding primitive type
and try to find an exact match, or widen the primitive type and find a match.
 
Search WWH ::




Custom Search