RSS Feed for This PostCurrent Article

Can I have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is already defined in the class.

Trackback URL

  1. 2 Comment(s)

  2. By Anshul on Feb 3, 2008 | Reply

    No the above given answer is wrong.
    A class can have many main methods provided they are overloaded ie having the same name as main but different arguments.
    And the compiler will successfully compile this program and also run the program using the main having the argument as String and leave the other mains as useless untill the main having String as arguments is calling the other mains which act as functions.

  3. By Niti on Aug 12, 2008 | Reply

    A class can have multiple main methods provided that they all have different arguments in terms of number and type.

    Program will compile successfully and at run time JVM will execute the main in which array of String has been passed as argument.We can call other methods from this main.

    for example-

    class Multiple_main
    {
    public static void main(String a[])
    {
    System.out.println(”Main 1″);
    main();
    }

    public static void main()
    {
    System.out.println(”Main 2″);
    main(3);
    }

    static void main(int a)
    {
    System.out.println(”Main 3—–” + a);
    }

    }

Post a Comment