开发者

What is the correct Java main() method parameters syntax?

Is there a functional difference between these methods?开发者_JAVA百科

public static void main(String[] args) { }

public static void main(String args[]) { }

EDIT (added this syntax from other contributors) :

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


No, but the first is the prefered style.

Edit: Another option is

public static void main(String... args)

which additionally allows callers to use varargs syntax.


Different Array notations

The notation

String args[]

is just a convenience for C programmers, but it's identical to this notation:

String[] args

Here's what the Sun Java Tutorial says:

You can also place the square brackets after the array's name:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Reference: Java Tutorial > Arrays

VarArgs

BTW, a lesser known fact is that main methods also support varargs, so this is also okay:

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

The reason is that a varargs method is internally identical to a method that supports a single array parameter of the specified type.E.g. this won't compile:

public static void main(final String... parameters){}
public static void main(final String[] parameters){}
// compiler error: Duplicate method main(String[])

Reference: Java Tutorial > Arbitrary Number of Arguments


There is no difference, but the first one is according to standard.


The other answers are correct in that it doesn't make a difference. Let me just add two further points:

String ... args is also valid now and in this case again makes no difference.

The different options to place your brackets do have a consequence, when you define multiple variables. In the following example the variable a is not a String array, but b is one and c is an array of arrays of Strings.

String a, b[], c[][];

However, I have to suggest not to use this style for your code, as it can quickly become very confusing. For example, String [] b, c[]; means the same for b and c as above, but especially for c this is non-obvious.


No, they have no difference. Though... I used to use the second way, until my girlfriend threatened to break if I continued doing it (not kidding). So now I prefer the first way, and I think it looks much better.


No, the above are equivalent. Arrays in Java can be declared in one of two ways, either:

String[] myarray;

or

String myarray[];


Use String[] instead of use [] postfix to reference. Infact String[] obj; hilights the fact that obj is a reference of type String[] (array of String).


I also prefer to mark the args as final.

public static void main(final String[] args) { }


There is not a difference between the 2 choices you can do either one of them.

You could also put this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜