Can you overload main() method in Java?

Yes, in Java, you can overload the main() method, which means that you can define multiple main() methods in a class with different parameter lists.

What is Method overloading

Method overloading is a powerful feature in Java that enables a class to have multiple methods with identical names but distinct parameter lists. This means you can define multiple methods within a class, as long as their input parameters vary in terms of number, type, or arrangement. Overloading facilitates code reusability and readability by providing more flexible ways to call methods, tailoring them to different data types or quantities of arguments. By utilizing method overloading effectively, Java programmers can create cleaner and more concise code while accommodating diverse scenarios and input requirements.

Overload main() method in Java

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists. When you overload the main() method, you are providing different entry points to your program, each with different input parameters.

Following is an example of overloading the main() method:

public class MainOverloadExample { public static void main(String[] args) { System.out.println("Main method with String array as argument (standard entry point)"); } public static void main(String arg) { System.out.println("Main method with String as argument"); } public static void main(int num) { System.out.println("Main method with int as argument"); } }

In this example, we have three different main() methods. The first one is the standard entry point for Java programs, which takes a String array as an argument. The other two methods are overloaded versions of main(), one taking a String argument and the other taking an int argument.

How to overload  main method in Java

When you run the MainOverloadExample class, Java will call the standard main() method with the String array argument by default. However, you can also call the other main() methods explicitly with appropriate arguments:

public class MainOverloadExample { // ... (as above) public static void main(String[] args) { System.out.println("Main method with String array as argument (standard entry point)"); // Call the other main methods explicitly main("Hello"); main(10); } }
Output: Main method with String array as argument (standard entry point) Main method with String as argument Main method with int as argument


Remember that when you run a Java program, you can only specify one entry point on the command line. However, the overloaded main() methods can still be called from within the program as regular methods. They are useful when you want to provide different ways to start the program or handle different types of input arguments.