Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "..." mean in Java? [duplicate]

I have been writing java for a while, and today I encountered the following declaration:

public static void main(String... args) {

}

Note the "dot dot dot" in the array declaration, rather than the usual bracket []. Clearly it works. In fact I wrote a small test and verified it works. So, I pulled the java grammar to see where this syntax of argument declaration is, but did not find anything.

So to the experts out there, how does this work? Is it part of the grammar? Also, while I can declare function like this, I can't declare an array within a function's body like this.

Anyway, do you know of any place that has this documented. It is curiosity, and perhaps not worth of any time invested in it, but I was stumped.

like image 971
Virtually Real Avatar asked Nov 18 '10 02:11

Virtually Real


2 Answers

I believe this was implemented in Java 1.5. The syntax allows you to call a method with a comma separated list of arguments instead of an array.

public static void main(String... args);
main("this", "is", "multiple", "strings");

is the same as:

public static void main(String[] args);
main(new String[] {"this", "is", "multiple", "strings"});

http://today.java.net/article/2004/04/13/java-tech-using-variable-arguments http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

like image 113
JohnS Avatar answered Nov 10 '22 01:11

JohnS


It is varargs

In simple term its an Array of Member like

public setMembers(Member[] members);

When to use:

Generally while designing API it is good to use when number of argument is not fixed.

Example from standard API of this is String.format(String format,Object... args)

Also See

  • var-arg-of-object-arrays-vs-object-array-trying-to-understand-a-scjp-self-test
like image 41
jmj Avatar answered Nov 10 '22 01:11

jmj