What is the difference between main (String ... s) and main (String [] s)?

class Test{ public static void main(String... s){ System.out.println("Hello"); } } class Test{ public static void main(String[] s){ System.out.println("Hello"); } } 

What is the difference between the two syntaxes of the main() declaration?

Does Java need a variable length argument?

+4
source share
4 answers

It makes no difference (when you run the program from the command line, i.e. the main method is used). The first option came after Java 5 introduced varargs .

In short, varargs allows you to pass a variable number of arguments to a method. For the method body, the arguments are grouped into an array. Like Test.main("foo", "bar") instead of Test.main(new String[] {"foo", "bar"}) . The compiler does the creation of an array for you behind the scenes.

+6
source

The only difference is that you call main directly from other Java code. The first form allows you to write:

 Test.main("first", "second", "third"); 

whereas for the second you will need to create an array explicitly:

 Test.main(new String[] { "first", "second", "third" }); 

Personally, I don’t think I have ever seen the first form used - calling main from another code is quite rare. There is nothing wrong.

+6
source

There is no difference.

In general, String... s allows you to pass arguments with a comma as a separator, and String[] s requires an array. But in the implementation of s there is an array in both cases. So ... is syntactic sugar in a sense.

+3
source

The changed number of arguments main(String... s) was introduced only in Java 5.0.

0
source

All Articles