There are following two valid signature of main method in java as below.
- public static void main(String args)
- public static void main(String… args) (As of Java 1.5)
Popular Spring Tutorials
- Spring Tutorial
- Spring MVC Web Tutorial
- Spring Boot Tutorial
- Spring JDBC Tutorial
- Spring AOP Tutorial
- Spring Security Tutorial
Why Java force the developer to define public static void main method?
Why public? In Java public is access modifier and it using when we want to method from any where like any native library JNDI, etc. So that is reason main method is public, it can be accessible everywhere and to every object which may desire to use it for launching the application.
Why static? In Java static is a keyword and it tells the compiler that particular entity belongs to a class and should be loaded once the JVM starts. So static things we could invoke without creating instance of that class. Lets suppose we do not have main method as static. Now, to call any method you need an instance of it. Now how to create instance of class which have main method and which one should be used and from where the parameters for overloaded constructors will come.
Why void? In Java void use before the method definition its mean this method is not returning any to the caller of method. But main method is invoked by JVM so there is no use of returning any value to JVM. The only thing application would like to communicate to invoking process normal or abnormal termination. This is already possible using System.exit(int). A non-zero value means abnormal termination otherwise everything was fine.
Why String args? it means we create a string type array. It is useful when we pass the value through command line while execute the program.
Why name is main? it is the special user define function. Although it is user define but We can’t change the name.
There are following conclusion we get.
- The main method must be declared public, static and void in Java otherwise JVM will not able to run Java program.
- Main method is entry point of core java application.
- Main mthod is invoked by main thread in JVM.
- Apart from static, void and public, you can use a final, synchronized and strictfp modifier in the signature of the main method in Java.
- You could overload the main method in java as other method loading but JVM invoke only specific signature method as listed above.
- static initializer call before JVM call main method.
- You can use throws clause in the signature of the main method.