Java main() Method

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

Since Java 21, we can create instance main() methods that do not require the public and static access modifiers, as well as, the method arguments are optional.

If we have not created the unnamed class, the discussion in this article still applies.

1. Java main() Method Syntax

Start with reminding the syntax of the 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?

This is a big question and perhaps most difficult to answer, too. I tried hard to find a good reason for this question in all the good learning material in my reach, but nothing proved enough.

So, my analysis says (like many others): 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 this exact similar reason because java.exe or javaw.exe (for windows) can use Java Native Interface (JNI) to execute the invoke method for calling the main() 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. The main() method also needs one. There is no reason why it should not be public, and be any other modifier(default/protected/private).

Notice that if we do not make main() method public, there is no compilation error. You will runtime error because the matching main() method is not present. Remember that the 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 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 minds 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 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. Let us 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 the main method in Java is to be a 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 the 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 happens when you invoke a java program with the main method.

8. Summary

Java’s main method is used by all developers and everybody knows the basic syntax to write it. Yet, very few completely understand the correct reasoning and the way it works.

In this post, we got a very basic understanding of the things behind the main method that is the primary starting point of an application.

Happy Learning!!

Comments

Subscribe
Notify of
guest
18 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode