varargs and the '...' argument varargs and the '...' argument arrays arrays

varargs and the '...' argument


From the docs on varargs:

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

So you can pass multiple arguments or an array.

The following works just fine:

class VarargTest {  public static void main(String[] args) {    Object[] params = {"x", 1.2345f};    String s = String.format("%s is %.2f", params);    System.out.println(s); // Output is: x is 1.23  }}


You can just pass an array:

public void foo(String... args) {}String args[] = new String[10];foo(args);


The situation you are describing is going to be fairly rare: most of the time, your varargs items will be Strings, or numbers, or Widgets... it will be unusual for them to be Objects (which could be anything) or arrays.

But if the varargs argument is a bunch of Objects or an array type, then your question does arise: you can pass it a single array and then how will the compiler know whether you meant to pass an array (the one you provided), or an series of 1 item which it should PUT into an array for you?

A quick test shows the answer:

public class TestClass {    public static void main(String[] args) {        Object anObject = new Object();        Object[] anArray = new Object[] {anObject, anObject};        System.out.println("object1 = " + anObject);        System.out.println("array1 = " + anArray);        takesArgs();        takesArgs(anObject, anObject);        takesArgs(anArray); // is this the same as array1?        takesArgs(anArray, anArray);    }    public static void takesArgs(Object... stuff) {        System.out.println("The array was " + stuff);    }}

The result of executing (your exact numbers will vary:

object1 = java.lang.Object@3e25a5array1 = [Ljava.lang.Object;@19821fThe array was [Ljava.lang.Object;@addbf1The array was [Ljava.lang.Object;@42e816The array was [Ljava.lang.Object;@19821fThe array was [Ljava.lang.Object;@9304b1

So the answer is that in ambiguous cases it treats what you passed as the array instead of creating a new array to wrap it. This makes sense as you could always wrap it in an array yourself if you wanted the other interpretation.