public static main (String args[]) 的变体
这 4 个方法签名有什么区别,为什么第 4 个方法签名不起作用?
public void main(String args[]) {... }
public void main(String[] args) {... }
public void main(String... args) {... }
public void main(String[] args[]) {... }
What is the difference between these 4 method signatures, and why does the 4th not work?
public void main(String args[]) {... }
public void main(String[] args) {... }
public void main(String... args) {... }
public void main(String[] args[]) {... }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
前三个是等价的。*最后一个相当于
String[][] args
(即数组的数组),这与Java的要求不符主要
。然而,惯用的版本是第二个。
* The third one is only valid from Java 5 onwards.
The first three are equivalent.* The last one is equivalent to
String[][] args
(i.e. an array of arrays), which doesn't match what Java requires formain
.However, the idiomatic version is the second one.
* The third one is only valid from Java 5 onwards.
String args[]
和String[] args
完全相同。第一种形式是数组声明的“C”形式,将[]
应用于变量名称。第二种形式是首选的 Java 形式,其中[]
(更逻辑地)与类型名称而不是变量名称相关联。 Java 允许这两种形式互换。第三种形式似乎是可变长度参数列表形式,尽管我从未深入研究过该领域。
第四种形式是一种令人憎恶的形式,只能从规范的缝隙中偷偷溜走,永远不应该使用。我的猜测是它指定了一个二维数组,但不尝试就无法确定。
请注意,
public static main
没有什么神圣之处。您可以将任何方法命名为main
并从任何地方调用它。只是当您从命令行运行 Java 程序时,JAVA 命令会查找具有该名称的内容(具有通常的参数布局)作为入口点。在此之前,main
被视为与任何其他方法一样。String args[]
andString[] args
are exactly equivalent. The first form is the "C" form of array declaration, with the[]
applied to the variable name. The second form is the preferred Java form, where the[]
is (more logically) associated with the type name rather than the variable name. Java allows both forms interchangeably.The third form appears to be a variable-length parameter list form, though I've never delved into that area.
The forth form is an abomination that only sneaks through the cracks of the spec and should never be used. My guess is that it specifies a 2-dimensional array, but one can't be sure without trying it.
Note that there's nothing sacred about
public static main
. You can name any methodmain
and call it from anywhere. It's just that when you run a Java program from the command line the JAVA command looks for something of that name (with the usual parameter layout) as the entry point. Up until thenmain
is treated like any other method.