Can We Have Multiple Main Methods in Java?
Java is an object-oriented language all processing is carried within classes. Execution of a program means dictates java virtual machine to load the class and then start execution of its main method. Java’s main method is entry point of any Java program. Public access modifier is used before the main method so that JVM can identify the execution point of the program. If other access modifiers are used instead of public, it will not be visible to JVM.
Initially, JVM loads the class but there is no object of the class present to call the main method. That is why the main method has to be static so that JVM can load the class and call the main method without having object of class. Java main method does not return anything that is why its return type is void. If we try to return anything from main method, it will give an unexpected value error because it is predefined signature in JVM. Java’s main method accepts string array as an argument. It is also called a command-line argument and it can pass from the command line in the main method. Now let us implement the same via appending clean java programs.
Inside class GFG
In the above program we are simply calling test() method by using class object from main() method. Now let us go onto depicting program having multiple main() methods.
Above program consist of two main methods but throws out an error that the Main method is not found in class, please define the main method as public static void main(String args)”. Only the main() method with a single string array as a parameter is considered as an entry point of the program. JVM only looks for main method with string array as an argument. In order for other main methods to execute, you need to call them from inside public static void main(String[ ] args)
From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.