public static void main(String[] args) {
System.out.println(fun(2,3,4));
}
static int fun(int a,int b,int c)
{
return 1;
}
static int fun(int ... a)
{
return 0;
}
Output:
1
Question:
In the above case why does the function fun select the 1st function and not the second.On what basis is the selection done since there is no way to determine which fun the user actually wanted to call ?
Basically there’s a preference for a specific call. Aside from anything else, this means it’s possible to optimize for small numbers of arguments, avoiding creating an array pointlessly at execution time.
The JLS doesn’t make this very clear, but it’s in section 15.12.2.5, the part that talks about a fixed arity method being more specific than another method if certain conditions hold – and they do in this case. Basically it’s more specific because there are more calls which would be valid for the varargs method, just as if there were the same number of parameters but the parameter types themselves were more general.