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

Ensom Hodder
  • 1,522
  • 5
  • 18
  • 35

2 Answers2

14

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

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

These are accepting only the instance of integer class for your test method which is not a primitive integer type of java. Integer is a class of java not the primitive type int like String class. On the other hand long is a primitive type and it has a subset of int so it chose that parameter as it is a closest match. You can try using double parameter as well. When int or long is signature is absence in a method parameter it chose to use the double's one as it is the closest match.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

try this:

public static void main(String[] args) {
    int i = 5;
    test(i);

    Integer smartInt= new Integer(5);
    test(smartInt); 
}
sadaf2605
  • 7,332
  • 8
  • 60
  • 103