Java Reference
In-Depth Information
Are you surprised by looking at the above output? Apply the rules that I have listed and you will find that the
above output followed those rules. The call to
test(101)
is clear because it widens 101 from
int
to
long
and executes
the
test(long)
method. To call
test(new Integer(101))
, it looks for a method
test(Integer)
and it does not
find one. Note that a reference type is never widened. That is, an
Integer
is never widened to
Long
. Therefore, it
unboxes the
Integer
to
int
and looks for
test(int)
method, which it does not find. Now, it widens the
int
and finds
test(long)
and executes it.
I have one more surprise. Consider the following two
test()
methods:
public void test(Long lObject) {
System.out.println("Long=" + lObject);
}
public void test(Object obj) {
System.out.println("Object=" + obj);
}
What will be printed when you execute the following code?
test(101);
test(new Integer(101));
This time, you will get the following output:
Object=101
Object=101
Does it make sense? Not really. Here is the explanation. When it calls
test(101)
, it has to box
int
to an
Integer
,
because there is no match for
test(int)
, even after widening the
int
value. So,
test(101)
becomes
test(Integer.
valueOf(101))
. Now it does not find any
test(Integer)
either. Note that
Integer
is a reference type and it inherits
the
Number
class, which in turn inherits the
Object
class. Therefore, an
Integer
is always an
Object
, and Java
allows you to assign an object of subtype
(Integer)
to a variable of supertype
(Object)
. This is the reason that
the
test(Object)
is called in this case. The second call,
test(new Integer(101))
, works the same way. It tries for
test(Integer)
method. When it does not find it, the next match for it is
test(Object)
based on the subtype and
supertype assignment rule for reference types.
Comparison Operators and AutoBoxing/Unboxing
I will discuss comparison operations
==
,
>
,
>=
,
<
,
<=
. Only
==
(logical equality operator) can be used with both
reference type and primitive types. The other operators must be used only with primitive types.
Let's discuss the easy ones (
>, >=, <
and
<=)
first. If a numeric wrapper object is used with these comparison
operators, it must be unboxed and the corresponding primitive type used in the comparison. Consider the following
snippet of code:
Integer a = 100;
Integer b = 100;
System.out.println("a : " + a);
System.out.println("b : " + b);
System.out.println("a > b: " + (a > b));