- Java main() Method
- Main Method in Java | public static void main(String[] args)
- Why public static void main in Java?
- Why do we need to declare main method as static in Java?
- Why main method is declared as static in Java?
- How to call main method in Java?
- Can we have more than one main() method in class?
- Can we execute a program without main() method in Java?
- Can we overload main method in java?
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.
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.
Error: Main method not found in class Main, please define the main method as: public static void main(String[] args)
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.
Error: Main method is not static in class main, please define the main method as: public static void main(String[] args)
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.
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)-&amp;amp;gt;GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V"); . .* Make sure the main method is public */ jint mods; jmethodID mid; jobject obj = (*env)-&amp;amp;gt;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)-&amp;amp;gt;CallStaticVoidMethod(env, mainClass, mainID, mainArgs);
So, here you can see what happens when you invoke a java program with the main method.
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.
Main Method in Java | public static void main(String[] args)
A main() method in java is an entry point to start the execution of a program. Every Java application has at least one class and at least one main method.
Normally, an application consists of many classes and only one of the class needs to have a main method.
In simple words, a complex program can have dozens of classes but only one of the classes needs to have a main() method to get things started. Therefore, java main() method is the starting place of your program.
The syntax for declaration of the java main method is as follows:
Syntax: public static void main(String[] args) < // Method body goes here. >
In the above declaration, two modifiers such as public, and static has been used with the main method. Let’s see a brief explanation and purpose of each of the terms used in the main method.
1. public : The public modifier makes it accessible from anywhere in the application.
2. static : The static modifier makes it a class method so that it can be called using the class name without creating an object of the class.
3. void : The return type of the main method is void which means that it does not return a value to its caller. You must specify void when you declare the main method.
4. main : It is the name of a method where execution will start. In Java, the main method is called by JVM.
5. String[ ] args : The main method accepts one argument of type String array (String[ ]). The square brackets [ ] represent the array of strings that is passed as an argument to this method.
args is the name of its parameter. You can use any parameter name as you wish.
For example, you can declare the main method like this public static void main(String[] myParameter), which is the same as declaring the main method as shown previously.
7. main Method Body : The region between the opening brace and closing brace is called main method body that contains a set of program statements. This region is a static region.
8. ( > ) : This is a closing brace that marks the closing of the main method body. It must be paired with an opening brace.
Why public static void main in Java?
Basically, the public static void main(String [ ] args) acts as an entry point to start the execution of Java application program. That’s why we use/write public static void main in java program.
Why do we need to declare main method as static in Java?
The main method is declared as static. It is called by JVM when we run a class. The JVM does not know how to create an object of a class. It needs a standard way to start the execution of a program.
Therefore, the main method is declared as static so that the JVM can call it using the class name which is passed on the command line.
Why main method is declared as static in Java?
If we do not declare the main method as static, it will be considered as an instance method. The code will be compiled successfully without generating any error message. But at runtime, the code will generate an exception named: “NoSuchmethodError: main”.
How to call main method in Java?
The main method is called by JVM when we run a class.
Can we have more than one main() method in class?
Yes, a class can have any number of main() methods but the execution always starts from public static void main(String[ ] args) only. Let’s take an example program where we will declare more than one method.
Program source code 1:
public class MainTest < public static void main(int a) < System.out.println("Second main() method"); main(); >public static void main() < System.out.println("Third main method"); >public static void main(String[] args) < System.out.println("main(String[] args)"); main(20); >>
Output: main(String[] args) Second main() method Third main method
In the above example program, we have declared three main() methods. The first main() method is declared as public static void main(String[] args) used as an entry point to run the program.
As far as JVM is concerned, the other two main() methods have no special significance. They have been declared only to print the message on the console.
Can we execute a program without main() method in Java?
Yes, we can execute a program without main() method in Java in the previous version of JDK. One of the ways is a static block. But from onwards JDK 1.7 and above, is not possible.
If the main() method has no argument of array reference of string type, the program source code will be compiled successfully without generating any error but at runtime, the program will terminate by generating an exception named: “NoSuchMethodError: main”.
Can we overload main method in java?
Yes, we can overload the main() method but we cannot override it. We can declare any number of main() method in a class, but the method signature must be different. Let’s make a program where we will overload the main method.
Program source code 2:
class OverloadMainMethod < public static void main(int a) // Overloaded main method < System.out.println(a); >public static void main(String args[]) < System.out.println("main method invoked"); main(10); >>
Output: main method invoked 10
1. public static void main(String args[ ]) is a line at which the program will start executing.
2. main() method in java is always called by JVM (Java Virtual Machine) before any objects are created.
3. It does not return any value.
4. Since Java is case-sensitive, Main is different from main. If you type Main instead of main, java compiler would still compile your program but java will report an error because it would not find main() method.
5. If a program does not contain the main method in a class, Java compiler will compile it but cannot run it.
6. Java main() method can be overloaded but cannot override it.