javaarraysvariablesmethodsarguments

Difference between vararg and array


Suppose, I have a code like this

public class HelloWorld {
    
    public static String method1(String[] array){return ""+array.length;}
    public static String method2(String... array){return ""+array.length;}
    
    
    public static void main(String args[]) {
        System.out.println(method1(new String[]{"test"})); //allowed
        //System.out.println(method1("test")); Not allowed
        System.out.println(method2(new String[]{"test"}));  //allowed
        System.out.println(method2("test")); //allowed
    }
}

When I do javap HelloWorld:

C:\Users\athakur\JavaProjectWorkspace\HelloWorld\bin\test>javap HelloWorld
Compiled from "HelloWorld.java"
public class test.HelloWorld extends java.lang.Object{
    public test.HelloWorld();
    public static java.lang.String method1(java.lang.String[]);
    public static java.lang.String method2(java.lang.String[]);
    public static void main(java.lang.String[]);
}

So, as per the class file, the method1() and method2() take same array argument. Then why the difference is in the input they can take?

Like method1() cannot take simple String input, where as vararg can take variable String inputs as well as an array?


Solution

  • So as per the class file method1 and method2 take same array argument.

    Yes, except there's extra metadata within the class file to indicate that the parameter for method2 is a varargs parameter. It's really just an extra bit of data on the parameter - that's all.

    You can detect it with reflection using Parameter.isVarArgs.

    All it means is that the compiler is willing to take a call like this:

    method2("test")
    

    and implicitly convert it into

    method2(new String[] { "test" })
    

    You don't always want that behaviour, so it has to be explicitly specified on the parameter using the varargs syntax.

    I suspect you're also using a slightly old version of javap, if it's not showing you the difference between the two method declarations. On my version (Java 8) I get:

    public static java.lang.String method1(java.lang.String[]);
    public static java.lang.String method2(java.lang.String...);