main Method in Java


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.

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
  • main() must be declared public because it is invoked by JVM whenever the program execution starts.
  • main() must be declared as static because if a method is declared as static then we can call that method outside the class using ClassName.methodName();
class Test
{
      public static void main(String[] args)
      {
                System.out.println("Hello");     
      }
}

The JVM will first Load the Test class,and will check for the Commandline arguments and calls the main method as Test.main();
  • main() must be declared as void main() because JVM is not expecting any value from main().So,it must be declared as void.
         If other return type is provided,the it is a RunTimeError i.e;NoSuchMethodFoundError.
  • main() must have String arguements as arrays because JVM calls main method by passing command line arguement.As they are stored in string array object it is passed as an argument to main().


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...