Why the value of type int does not fit as Integer

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 tell me why this is not an "Integer", since in Java the value of int should be automatic.

+4
source share
2 answers

When the compiler has the choice of extending int to long or box int as Integer , it selects the cheapest conversion: extending to long . The conversion rules in the context of a method call are described in section 5.3 of the Java language specification and the rules for choosing a matching method, when there are several possible matches described in section 15.12.2 (in particular, section 15.12.2.5 , but it should be warned that this is a very dense read).

+14
source

They only accept an instance of the integer class for your test method, which is not a primitive integer java type. integer is a java class, not a primitive int like a String class. long , on the other hand, is a primitive type and has a subset of int , so it selects this option because it is the closest match. You can also try using a double parameter. When int or long is the absence signature in the method parameter, he decided to use double alone, as this is the closest match.

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

try the following:

 public static void main(String[] args) { int i = 5; test(i); Integer smartInt= new Integer(5); test(smartInt); } 
0
source

All Articles