Why is the main () method special in a java program?

The main method in Java is the first programming method a Java programmer knows when he starts learning Java programming language. have you ever thought about why the main method in Java is public, static, and void, of-course Yes, since most of us first learn C and C++ than we move to Java in our programming path we familiar with the main method but in Java main method is slightly different it doesn't return any value like in C it returns an int, the main method is public static and void Why?

In this post, we will try to find answers to these questions and have an idea of one of the most popular questions in Java why the main method is declared Static.

The main method in Java is the entry point for any core Java program. Remember we are not talking about Servlet, MIDlet, or any other container-managed Java program where life cycle methods are provided to control the execution. 

In core Java program, execution starts from the main method when you type java main-class-name, JVM search for public static void main(String args[]) method in that class, and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.

Signature of the main method in Java

The main method has to strictly follow its syntax; otherwise, JVM will not be able to locate it and your program will not run. Here is the exact signature of the main method



public static void main(String args[])

This signature is a classic signature and there from the start of Java but with the introduction of  variable argument or varargs in Java5 you can also declare the main method in Java using varargs syntax as shown in the below example:

public static void main(String... args)

Remember varargs version of the java main method will only work in Java 1.5 or later versions. 

Apart from the public, static and void, there are certain keywords like final, synchronized, and strictfp which are permitted in the signature of the java main method.

Why is the main () method special in a java program?
Now come to the main point "Why the main method is static in Java", there are quite a few reasons around but here are few reasons which make sense to me:

1. Since the main method is static Java Virtual Machine can call it without creating an instance of a class that contains the main method.

2. Since C and C++ also have a similar main method which serves as an entry point for program execution, following that convention will only help Java.

3. If the main method were not declared static then JVM has to create an instance of the main Class and since the constructor can be overloaded and can have arguments there would not be any certain and consistent way for JVM to find the main method in Java.

4. Anything which is declared in class in Java comes under reference type and requires objects to be created before using them but the static method and static data are loaded into separate memory inside JVM called context which is created when a class is loaded. If the main method is static then it will be loaded in the JVM context and are available for execution.


Why the main method is public in Java

Java specifies several access modifiers e.g. private, protected, and public. Any method or variable which is declared public in Java can be accessed from outside of that class. Since the main method is public in

Java, JVM can easily access and execute it.

Why the main method is void in Java

Since the main method in Java is not supposed to return any value, it's made void which simply means main is not returning anything.

Summary:

1. The main method must be declared public, static and void in Java otherwise, JVM will not able to run Java program.

2. JVM throws NoSuchMethodException:main if it doesn't find the main method of predefined signature in class which is provided to Java command. E.g. if you run java Helloworld than JVM will search for public static void main String args[]) method in HelloWorld.class file.

3. The main method is an entry point for any Core Java program. Execution starts from the main method.

4. The main method is run by a special thread called "main" thread in Java. Your Java program will be running until your main thread is running or any non-daemon thread spawned from the main method is running.

5. When you see "Exception in Thread main” e.g.

Exception in Thread main: Java.lang.NullPointerException it means Exception is thrown inside main thread.

6. You can declare the main method using varargs syntax from Java 1.5 onwards e.g.

public static void main(String... args)

7. Apart from static, void, and public, you can use a final, synchronized and strictfp modifier in the signature of the main method in Java.

8. The main method in Java can be overloaded like any other method in Java but JVM will only call the main method with the specified signature specified above.

9. You can use the throws clause in the signature of the main method and can throw any checked or unchecked Exception.

10. A static initializer block is executed even before JVM calls the main method. They are executed when a Class is loaded into Memory by JVM.

Some tutorials you may like

How to Split String in Java Program

How Substring in Java Works

How to debug Java Program in Eclipse – Tips

String Replace Example in Java

Factory Pattern in Java with Example

Decorator Pattern in Java with Example

Top 15 Thread interview questions in Java

In order to continue enjoying our site, we ask that you confirm your identity as a human. Thank you very much for your cooperation.

In Java programs, the point from where the program starts its execution or simply the entry point of Java programs is the main() method. Hence, it is one of the most important methods of Java and having a proper understanding of it is very important.

The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.

The execution of the Java program, the java.exe is called. The Java.exe inturn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program stops execution.

Why is the main () method special in a java program?

Syntax: Most common in defining main() method

class GeeksforGeeks {

    public static void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Output explanation:  Every word in the public static void main statement has got a meaning to the JVM. 

1. Public 

It is an Access modifier, which specifies from where and who can access the method. Making the main() method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.

class GeeksforGeeks {

    private static void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

2. Static

It is a keyword that is when associated with a method, making it a class-related method. The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.

class GeeksforGeeks {

    public void main(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

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

3. Void 

It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn’t make any sense to return from the main() method as JVM can’t do anything with the return value of it.

class GeeksforGeeks {

    public static int main(String[] args)

    {

        System.out.println("I am a Geek");

        return 1;

    }

}

Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

4. main 

It is the name of the Java main method. It is the identifier that the JVM looks for as the starting point of the java program. It’s not a keyword.

class GeeksforGeeks {

    public static void myMain(String[] args)

    {

        System.out.println("I am a Geek");

    }

}

Error: Main method not found in class, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

5. String[] args 

It stores Java command-line arguments and is an array of type java.lang.String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it. 

class GeeksforGeeks {

    public static void main(String[] args)

    {

        for (String elem : args)

            System.out.println(elem);

    }

}

Output:

1 2 3

Apart from the above-mentioned signature of main, you could use public static void main(String args[]) or public static void main(String… args) to call the main function in Java. The main method is called if its formal parameter matches that of an array of Strings.

Can the main method be int? If not, why?

class GeeksforGeeks {

public static int main(String[] args)

    {

        System.out.println("GeeksforGeeks");

    }

}

 
Java does not return int implicitly, even if we declare the return type of main as int. We will get a compile-time error: 

prg1.java:6: error: missing return statement } ^ 1 error

class GeeksforGeeks {

   public static int main(String[] args) {

       System.out.println("GeeksforGeeks");

       return 0;

   }

}

Now, even if we do return 0 or integer explicitly ourselves, from int main. We get a run time error.

Error: Main method must return a value of type void in class GeeksforGeeks, please define the main method as: public static void main(String[] args)

Explanation: 

The C and C++ programs which return int from main are processes of Operating System. The int value returned from main in C and C++ is exit code or exit status. The exit code of the C or C++ program illustrates, why the program was terminated. Exit code 0 means successful termination. However, the non-zero exit status indicates an error. 

For Example exit code 1 depicts Miscellaneous errors, such as “divide by zero”.

The parent process of any child process keeps waiting for the exit status of the child. And after receiving the exit status of the child, cleans up the child process from the process table and free the resources allocated to it. This is why it becomes mandatory for C and C++ programs(which are processes of OS) to pass their exit status from the main explicitly or implicitly.

However, the Java program runs as a ‘main thread’ in JVM. The Java program is not even a process of Operating System directly. There is no direct interaction between the Java program and Operating System. There is no direct allocation of resources to the Java program directly, or the Java program does not occupy any place in the process table. Whom should it return an exit status to, then? This is why the main method of Java is designed not to return an int or exit status.

But JVM is a process of an operating system, and JVM can be terminated with a certain exit status. With help of java.lang.Runtime.exit(int status) or System.exit(int status).

Can we execute a java program without main method?

Yes, we can execute a java program without a main method by using a static block.

A static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by ClassLoader, It is also known as a static initialization block, and it goes into the stack memory.

class StaticBlock { static { System.out.println( "This class can be executed without main"); System.exit(0); } }