Can we overload main() method in Java?

Yes, We can overload the main() method. A Java class can have any number of main() methods. But to run the java class, the class should have main() method with signature as public static void main(String[] args).
The below diagram demonstrates that the main() method can be overloaded:

Example: main() method overloaded

Let's see a simple example to demonstrates main() can be overloaded:
package net.javaguides.corejava;

import java.util.Arrays;

public class MainMethodDemo {

    /** Actual main method with String[] args**/
    public static void main(String[] args) {
        System.out.println("String[] args main method called");
        main(new Double[] {
            1.0,
            2.0,
            3.0
        });
    }

    /** Overloaded main method with Double[] args**/
    public static void main(Double[] args) {
        System.out.println("Double[] args main method called");
        System.out.println(Arrays.toString(args));
    }
}
Output:
String[] args main method called
Double[] args main method called
[1.0, 2.0, 3.0]

Comments