public class Test
{
public static void printValue(int i, int j, int k)
{
System.out.println("int");
}
public static void printValue(byte...b)
{
System.out.println("long");
}
public static void main(String... args)
{
byte b = 9;
printValue(b,b,b);
}
}
The output of the above code is "int". But it should be "long" because byte type argument function is already present. But here the program is promoting the byte values to int, but it should not be the case.
Please can someone clarify what is going on here?
JLS 15.12.2 is the relevant bit of the spec to look at here. In particular - emphasis mine:
In your case, the first phase finds a match without using variable arity method invocation or boxing, hence that's the result. As noted in the spec, this is basically for backward compatibility.
Variable argument methods will always be the last one to be chosen by the compiler in case of overloaded methods. Promotion of a
byte
to anint
(widening-conversion) will be preferred over the method that takes a var-arg parameter.The reason behind this is that the language needs to be backward compatible. Older features will take priority over newer features. A simple way of understanding what the JLS says about variable arguments is that widening will beat boxing and boxing will beat var-args.