variations on public static main (String args[])

隐身守侯 提交于 2020-01-05 23:36:44

问题


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[]) {... }

回答1:


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 for main.

However, the idiomatic version is the second one.


* The third one is only valid from Java 5 onwards.


回答2:


String args[] and String[] 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 method main 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 then main is treated like any other method.



来源:https://stackoverflow.com/questions/8290492/variations-on-public-static-main-string-args

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!