Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why int type value is not boxed as Integer [duplicate]

Tags:

java

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.

like image 950
Ensom Hodder Avatar asked Dec 09 '22 17:12

Ensom Hodder


1 Answers

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).

like image 196
Ted Hopp Avatar answered Dec 11 '22 10:12

Ted Hopp