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?
Why do we usually start programs with public static void main('String[] args')?
249 views Asked by MasterWali At
2
There are 2 answers
2
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 declaredpublic
,static
, andvoid
. It must specify a formal parameter (ยง8.4.1) whose declared type is array ofString
. 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.
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 yourmain
.