Can there be more than one main method in a Java Program

Yes, you can have as many main methods as you like. You can have main methods with different signatures from main(String[]) which is called overloading, and the JVM will ignore those main methods.

You can have one public static void main(String[] args) method in each class. Some people use those methods for testing. They can test the operation of each class individually. The JVM will only invoke the public static void main(String[] args) method in the class you name when you write java MyClass.

public class TwoMain {  
    public static void main(String args1[])  
    {  
        System.out.println("First main");  
  
    }  
    public static void main(String args2[])  
    {  
        System.out.println("Second main");  
  
    }  
  
} 

Those two methods have the same signature. The only way to have two main methods is by having two different classes each with one main method. The name of the class you use to invoke the JVM (e.g. java Class1, java Class2) determines which main method is called.

2 Thoughts on “Can there be more than one main method in a Java Program

  1. pablo on June 5, 2020 at 10:18 am said:

    No, you can’t. That code is invalid. You can’t override a method with the *same” list of types. Name of parameters doesn’t matter, but parameter’s types must be different. Or count of parameters must be different. You can’t have the same list of parameters types and count on the same class.
    You can have one main per class, but no more than one.

  2. Divyanshu on September 12, 2021 at 5:37 pm said:

    No Yo can not define two main method in a Java Program.
    public class TwoMain {

    public static void main1(String[] args) {
    // TODO Auto-generated method stubo

    System.out.println(” HI First main”);

    }

    public static void main2(String[] args) {
    // TODO Auto-generated method stubo

    System.out.println(” HI First main 2″);

    }

    }

    == error

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation