Search code examples
javaarraysvariadic-functions

Is a variable length argument treated as an array in Java?


As I understand an array consists of fixed number of elements and a variable length argument takes as many number of arguments as you pass (of the same type). But are they same? Can I pass one where the other is expected?


Solution

  • Yes, if you have a method with a varargs parameter like this:

    public void foo(String... names)
    

    and you call it like this:

    foo("x", "y", "z");
    

    then the compiler just converts that into:

    foo(new String[] { "x", "y", "z"});
    

    The type of the names parameter is String[], and can be used just like any other array variable. Note that it could still be null:

    String[] nullNames = null;
    foo(nullNames);
    

    See the documentation for varargs for more information.

    This does not mean that varargs are interchangeable with arrays - you still need to declare the method to accept varargs. For example, if your method were declared as:

    public void foo(String[] names)
    

    then the first way of calling it would not compile.