A mini guide to main method in java

Have you ever tried to reason, why main method in java is public, static and void? I tried to find out and after some analysis, below are my findings. Please feel free to add if i am missing anything, I will update this post.

Sections in this post:

  1. Why public?
  2. Why static?
  3. Why void?
  4. Why the name is main?
  5. What happens when you invoke main method
  6. Lets peek in code
  7. Do we always need main method to run java program
  8. Summary

Why public?

Big question and perhaps most difficult too. I tried hard to find a good reason for this question in all good learning material in my reach, but nothing proved enough. So, my analysis says (like many others): 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 method, so they can have invoked it either way irrespective of any access modifier.

Second way to answer this is another question, why not public? All methods and constructors in java have some access modifier. main() method also need one. There is no reason why it should not be public, and be any other modifier(default/protected/private).

Why static?

Another big question. To understand this, let suppose we do not have 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. These are just more difficult questions, which helped Java designers to make up their mind and to have main method as static.

Why void?

Why it should not be void? Have you called this method from your code? NO. Then there is no use of returning any value to JVM, who actually invokes this method. It simply doesn’t need any reaturning value.

The only thing application would like to communicate to invloking 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.

Why the name is main?

No rock solid reason. Lets assume because it was already in use with C and C++ language. So, most developers were already comfortable with this name. Otherwise there is not other good reason.

What happens when you invoke main method

When you run java.exe, then there are a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that’s right -- java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge between the virtual machine world, and the world of C, C++, etc.. The reverse is also true. It is not possible (at least to my knowledge) to actually get a JVM running without using JNI.

Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java, it just uses confusingly named native function calls instead.

It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK), and have it do something entirely different.

Source: StackOverflow

Lets peek in code also

Download and extract the source jar and check out ../launcher/java.c. It is something like this:


/*
* Get the application's main class.
*/
if (jarfile != 0) {
mainClassName = GetMainClassName(env, jarfile);
... ...

mainClass = LoadClass(env, classname);
if(mainClass == NULL) { /* exception occured */
... ...

/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V");
... ...

{/* Make sure the main method is public */
jint mods;
jmethodID mid;
jobject obj = (*env)->ToReflectedMethod(env, mainClass, mainID, JNI_TRUE);
... ...

/* Build argument array */
mainArgs = NewPlatformStringArray(env, argv, argc);
if (mainArgs == NULL) {
ReportExceptionDescription(env);
goto leave;
}

/* Invoke main method. */
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);

So, here you can see what actually happen when you invoke a java program.

Do we always need main method to run java program

I believe not. We do have applets, where we do not write the main method. I still need to check how they are executed. If you already knew, please share with me.

Summary

Java’s main method is used by all developers and everybody know the basic syntax to write it. Yet, very few completely understand the correct reasoning and the way it works. I am still trying to figure out more understanding and will update this post if found more interesting facts.
If you have something to share please add in comments section or send me a mail. I will get included your knowledge in this post.

Happy Learning!!

 

Ads by Google

11 thoughts on “A mini guide to main method in java”

  1. /*
    * Entry point.
    */
    int
    JLI_Launch(int argc, char ** argv, /* main argc, argc */
    int jargc, const char** jargv, /* java args */
    int appclassc, const char** appclassv, /* app classpath */
    const char* fullversion, /* full version defined */
    const char* dotversion, /* dot version defined */
    const char* pname, /* program name */
    const char* lname, /* launcher name */
    jboolean javaargs, /* JAVA_ARGS */
    jboolean cpwildcard, /* classpath wildcard*/
    jboolean javaw, /* windows-only javaw */
    jint ergo /* ergonomics class policy */
    )

    I went through this file java.c I show there is no main method i.e int main(int argc, char **argv, …). in java.c file they are saying JLI_Launch is entry point so i am little bit confused is it first entry point ? or some other method ? and that method is calling this method(JLI_Launch ) please clear it I am very curious to know when I write “java mainClass” command on cmd who is the first guy that receive these inputs ? and how it process ?

  2. This was a nice post.loved it….but i still have a doubt about it if we do not use static keyword with main .we simply use public void main() in this case compilation succeeds but it causes run time exception thats a null pointer exception .Why this happens.????

    1. Abhi JVM invokes the main method using native code and does not need access permissions to invoke this method. Even if main method is private, you call call it from native code without any problem.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?