Can we have multiple main methods in Java ?
Points to remember
- We can have only one entry point per class in Java. Thus we can have only one "public static void main(String args[])".
- Any other method with a different name or type or arguments will not be treated as a main method().
Example
What will be the output of the following program ??
public class TestClass{ public static final void main (String args[]){ System.out.println("Hello World String args[]"); } public void main (String args){ System.out.println("String args"); } public void main (Integer args){ System.out.println("Integer args"); } }This class will compile successfully and will give a output Hello World String args[]
What will be the output of the following program ??
public class TestClass{ public void main (String args){ System.out.println("String args"); } public void main (Integer args){ System.out.println("Integer args"); } }This class will also compile successfully but will give a run time exception, "Main method not found in class TestClass, please define the main method".
Thus none of the above methods acted as an entry point for execution, since they are just another method by the name main, but not the main method JVM looks for.
No comments: