How does the Java array argument declaration synta

2019-01-04 15:18发布

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.

10条回答
女痞
2楼-- · 2019-01-04 15:35
乱世女痞
4楼-- · 2019-01-04 15:38

It's called varadic argument: A function that takes as many (including zero) arguments as you want. For example, main("string1", "string2", "string3") is same as main({"string1", "string2", "string3"}) if main is declared as void main(String...args).

See http://www.java-tips.org/blog/java-se/varargs-%E2%80%93-java-50-addition.html

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-04 15:42

It means that the method accepts a variable number of String arguments. The arguments are treated as an array and so are accessed by subscript, in the order they are passed in.

查看更多
登录 后发表回答