Why do we usually start programs with public static void main('String[] args')?

249 views Asked by At

I understand why public static void main is used, I also know that String[] args creates a 1-D array called args which contains strings. But why must we have this with in the parenthesis?

2

There are 2 answers

0
Zizouz212 On

The String[] args is to supply all the arguments that may be delivered to your program from the command line. Say for example you wanted a filepath as a parameter to your main, you can type it with the command line and it will pass that as the first element in the array. It allows you to pass nothing, or many things when running your main.

2
rgettman On

The Java language was specified that the main method must take exactly one parameter of type String[]. It can be named any valid identifier you want; it's only a convention that it's named args. It can even be String.... Here's the specification, from the JLS, Section 12.1.4:

The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

public static void main(String[] args)

public static void main(String... args)

It could even be

public static void main(String[] zzyzx)

but the parameter must be there.