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().
Yes, we can have multiple main methods in a java class. Surprised ?? Method Overloading, by using this you can have as many main() methods as you want as long as their types or arguments are different. However these are not actually the main() methods, these are just overridden methods and may act as any other overridden method. None of these will be treated as an entry point for execution.

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 :

Post a Comment