Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

syntax

Is there a functional difference between these methods?

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) { }
like image 280
james Avatar asked Nov 03 '10 17:11

james


3 Answers

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.

like image 173
starblue Avatar answered Oct 11 '22 06:10

starblue


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

like image 34
Sean Patrick Floyd Avatar answered Oct 11 '22 06:10

Sean Patrick Floyd


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

like image 20
Vivin Paliath Avatar answered Oct 11 '22 04:10

Vivin Paliath