Java main() method

Have you ever tried to reason why Java main method is public, static and void? Why it’s name is main? What happens inside JVM when you invoke main() method? What is the purpose of main method? Let’s find out.

Table of Contents

1. Java main method syntax
2. Why main method is public?
3. Why main method is static?
4. Why main method is void?
5. Why the name is main?
6. What happens internally when you invoke main method?
7. main() method native code in java.c
8. Do we always need main method to run java program?
9. Summary

1. Java main method syntax

Start with reminding the syntax of main method in Java.

public class Main 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello World !!");
    }
}

2. Why Java main method is public?

The 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.

A 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).

Notice that if you do not make main() method public, there is no compilation error. You will runtime error because matching main() method is not present. Remember that whole syntax should match to execute main() method.

public class Main 
{
    void static main(String[] args) 
    {
        System.out.println("Hello World !!");
    }
}

Program Output:

Error: Main method not found in class Main, please define the main method as:
   public static void main(String[] args)

3. Why Java main method is static?

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

Notice that if you do not make main() method static, there is no compilation error. You will runtime error.

public class Main 
{
    public void main(String[] args) 
    {
        System.out.println("Hello World !!");
    }
}

Program Output:

Error: Main method is not static in class main, please define the main method as:
   public static void main(String[] args)

4. Why Java main method is void?

Why should it 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 returning value.

The only thing 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.

5. 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 no other good reason.

6. What happens internally when you invoke main method?

The purpose of main method in Java is to be program execution start point.

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 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.

7. main() method native code in java.c

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 happen when you invoke a java program with main method.

8. 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.

9. 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 the comments section or send me a mail. I will get included in your knowledge in this post.

Happy Learning!!

References: StackOverflow

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

20 thoughts on “Java main() method”

  1. A Java program is a sequence of Java instructions that are executed in a certain order. Since the Java instructions are executed in a certain order, a Java program has a start and an end.

    Reply
  2. I believe, the rational behind enforcing main as public is more to do with the language specification – rather than whether something could be achieved otherwise or not.

    Reference

    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. Therefore, either of the following declarations is acceptable:

    Of course the JNI way to launch java application will never have any issue in calling a private main – but this is more like jail-brake (like another jail-brake, where reflection API let you access private method) and definitely not in spirit of java specification.

    Reply
      • Actually, if I remember till JDK 1.3 – it was not mandatory from developer’s perspective. i.e. even a private main was being accepted by JRE. Though, it was not inline with JLS 1.3.

        I tried searching JLS 1.3 for a reference, but could not get a link. But I found that it was reported as a bug by developers across world:

        Please refer: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4155575

        So, a fix was made in subsequent version to enforce rule stated by JLS.

        Now, the point is why JLS writer enforced this rule at first place – I really have no idea. The only thing I can think of is that – to keep it “obvious” and non-confusing for developers; which boils down to your paragraph starting with : Second way to answer this is another question, why not public….

        Obviously, the next best convention could have been to keep it into default access scope; but definitely not in protected/private scope (which will simply create more “difficult” question – Why main should be private/protected…)

        Reply
        • To add more; the JVM specification too has rules for JVM vendor; preventing them to write any incompatible JVM (which may allow a non-public main).

          Reference: https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.2

          The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (§5.3.1). The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution.

          In this way Sun (now Oracle) closed all the door for any ambiguity.

          Reply
  3. Thanks and some assumptions

    Thank u very much for sharing your knowledge…I m not familiar with applets but i defiantly sure that applet should also have any initial point like Servlet’s init() method that’s why they don’t need main() method.

    Reply
  4. 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.


    My opinion is that any java source code which is not having main() method but correctly implements certain contracts like Applet, Swing, Servlet, EJB runs in a managed environment and has lifecycle callbacks which are automatically invoked by the runtime environments like servlet container(Servlet), browser having jre plugin installed(Applet), JNLP protocol(which also needs a suitable pre-installed JRE) for remote swing code or JRE for local swing code, J2EE server/app server for EJB.

    Reply
  5. /*
    * 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 ?

    Reply
  6. 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.????

    Reply
    • 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.

      Reply
  7. These are really good points. The reference main methodand this article really completes everything there to know about main method

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.