Why can't we just use arrays instead of varargs?

The only difference between

foo(String... strings)

and

foo(String[] strings)

is for the calling code. Consider this call:

foo("a", "b");

That's valid with the first declaration of foo, and the compiler will emit code to create an array containing references to "a" and "b" at execution time. It's not valid with the second declaration of foo though, because that doesn't use varargs.

In either case, it's fine for the caller to explicitly create the array:

for(new String[] { "a", "b" }); // Valid for either declaration

Also does main(String[] args) in java use varargs , if not how are we able to pass runtime parameters to it

When it's written as main(String[] args) it doesn't; if you write main(String... args) then it does. It's irrelevant to how the JVM treats it though, because the JVM initialization creates an array with the command line arguments. It would only make a difference if you were writing your own code to invoke main explicitly.


We could use arrays instead of varargs. Varargs are syntactic sugar for using arrays. But they make your code more compact and more readable. Compare

private void foo(String... ss) { ... }

private void bar() {
    ...
    foo("One", "Two", "Three");
    ...
}

with

private void foo(String[] ss) { ... }

private bar() {
    ...
    foo(new String[] { "One", "Two", "Three" });
    ...
}

Similarly, we don't need the diamond operator (<>, Java 7) or lambdas (Java 8) either. But they do make code more readable and therefore more maintainable.


One advantage of varargs is for methods requiring at least one parameter, such as max. With varargs you can do it like this

static int max(int first, int... remaining) {
    int max = first;
    for (int number : remaining)
        max = Math.max(max, number);
    return max;
}

This is great, because it is impossible to pass no parameters to the max method, and the calling code for max is really clean: max(2, 4, 1, 8, 9). Without varargs the only way to have enforced the condition that at least one number should be passed would have been to have thrown an exception at runtime if the array had length 0 (always best avoided) or to force the caller to write max(2, new int[] {4, 1, 8, 9}) which is really ugly.