Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable argument in java

Tags:

java

public class Demo {
    public static String doit(int x,int y)
    {
        return"a";
    }
    public static String doit(int ...val)
    {
        return "b";
    }
    public static void main(String args[])
    {
        System.out.println(doit(4,5));
    }
}

I have a doubt that why compilier is not showing any error since doit(4,5) is causing ambiguity

When I ru the code ,I get output as a ad not b why?

like image 418
coder25 Avatar asked Mar 06 '12 10:03

coder25


2 Answers

The Java Language Specification defines that first method ("a") should be called (rather than "b").

See http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.12.2

In order to maintain backwards compatibility with previous Java versions (before varargs was introduced), the compiler will always pick a method with the exact number of arguments, even if a varargs method also exists.

As to whether you get a warning or not, compilers are free to add additional warnings, and there may be some that do warn about this situation, I guess yours doesn't (at least not with the settings you have)

like image 172
Tim Avatar answered Oct 05 '22 23:10

Tim


The JLS specifies the rules that are used to resolve ambiguity. The simplified version is that the compiler first attempts to match the call against the available overloads treating the varadic argument as a simple array. If that succeeds, that is it. If it fails, it tries again treating the last argument as varadic.

In this case, the first round of matching gives a definite match.

If you are interested, the JLS rules for determining what method should be used are given in Section 15.12.2. (Warning: actual JLS rules are significantly more involved than the simplified version above, and the language / notation used is very technical.)

like image 27
Stephen C Avatar answered Oct 05 '22 23:10

Stephen C