public class Test {
static void test(Integer x) {
System.out.println("Integer");
}
static void test(long x) {
System.out.println("long");
}
static void test(Byte x) {
System.out.println("byte");
}
static void test(Short x) {
System.out.println("short");
}
public static void main(String[] args) {
int i = 5;
test(i);
}
}
The output value is "long".
Can only tells me why it is not "Integer" since in Java, int value should be auto-boxed.
When the compiler has a choice of widening an int
to a long
or boxing an int
as an Integer
, it chooses the cheapest conversion: widening to a long
. The rules for conversion in the context of method invocation are described in section 5.3 of the Java language specification and the rules for selecting the matching method when there are several potential matches are described in section 15.12.2 (specifically section 15.12.2.5, but be warned that this is very dense reading).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With