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

I just came across varargs while learning android(doInBackground(Type... params)) ,SO posts clarified the use of it

My question is why can't we just use Arrays instead of varargs

public void foo(String...strings) {  }

I can replace this type of a call by packing my variable number of arguments in an array and passing it to a method such as this

public void foo(String[] alternativeWay){  }

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

Please suggest the benefits or use of varargs and is there there anything else important to know about varargs

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow