I have the following code:
public static void main(String ... args) {
int valor = 30;
metodoSobrecargado(valor);
}
private static void metodoSobrecargado(long valor) {
System.out.println("Primitivo long.");
}
private static void metodoSobrecargado(Integer valor) {
System.out.println("Clase Integer.");
}
When run with Java 7, it prints 'Primitive long.', but I can't explain why this happens. Shouldn't it print 'Class Integer.' due to the autoboxing that Java does by converting the variable of type integer valor
to its wrapper Integer
and selecting the method metodoSobrecargado
that receives an object of this type as a parameter?
The reason is that Java will prefer the conversion of primitive types before boxing, that is, since no overload is received,
int
it will prefer to cast tolong
(Widening Primitive Conversion) before boxing toInteger
(Boxing Conversion) .Instead if the code were:
Or if the second method were declared like this:
So the types would consider either int or integer and therefore the expected overload would be called.
According to the Java 7 specification:
My translation:
In other words, when the argument
int
has to be converted to the type of the parameter , the widening primitive conversion (from tolong
)Integer
is chosen first, according to the list , before the boxing conversion (from to ) .int
long
int
Integer