What is the reason main() in java is declared as public static void


Why public? the main method is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application. Here, I am not saying that JDK/JRE had similar reasons because java.exe or javaw.exe (for windows) use Java Native Interface (JNI) calls to invoke a method, so they can have invoked it, either way, irrespective of any access modifier.

Why static? Let's suppose we do not have the main method as static. Now, to invoke any method you need an instance of it. Right? Java can have overloaded constructors, we all know. Now, which one should be used and from where the parameters for overloaded constructors will come.

Why void? Then there is no use of returning any value to JVM, who actually invokes this method. The only thing the application would like to communicate to the invoking process is normal or abnormal termination. This is already possible using System.exit(int). A non-zero value means abnormal termination otherwise everything was fine.

Related Articles

post a comment