From Java Language Specification 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)
(note that you can't have two main
methods with String[]
and String...
in same class, since varargs are simply syntactic sugar which at compilation time will be replaced with arrays so you would end up with two methods handing String[]
and one class can't have two methods with same name and parameters)
So when you execute command like
java YourClass foo bar
Java Virtual Machine will place foo
and bar
parameters in String[]
array and will try to pass that array to main
method which can accept it as parameter.
This method is also used when command doesn't have any arguments like
java YourType
This decision simplifies our life because we don't need to focus on handling cases where there are two entry points
- one for command with arguments
- and one where command doesn't have any arguments.
We can simply allow user to pass arguments but if we don't wan to handle them we can simply ignore them.
Also remember that we are allowed to have in our class any method which has proper declaration (and doesn't violate any rules inherited from superclass like widening member visibility - we can't make protected method public), so there is nothing wrong with having
public static void main(){
/*your code*/
}
But you need to realize that this method can't be used as entry point, so if you want to start your application from this method you will need to create proper main
method which will execute your main()
method:
public static void main(String ...){
main();
}