public static void main(String arg[ ] ) in java is it fixed?

The signature of the main method is specified in the Java Language Specifications section 12.1.4 and clearly states:

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.

  • it must be public otherwise it would not be possible to call it
  • it must be static since you have no way to instantiate an object before calling it
  • the list of String arguments is there to allow to pass parameters when executing a Java program from the command line. It would have been possible to define it without arguments but is more practical like that (and similar to other languages)
  • the return type is void since it does not make sense to have anything else: a Java program can terminate before reaching the end of the main method (e.g., by calling System.exit())

The method signature can therefore be:

public static void main( String[] args )
public static void main( String... args )

note that the varargs version (...) is only valid from Java 5

As the Java language allows the brackets [] to be positioned after the type or the variable (the first is generally preferred),

public static void main( String args[] ) // valid but usually non recommended

is also valid

Leave a Comment