Can we overload the main method in java

Yes, we can overload the main method, and here we will see the overloading main method in java. But before start with this post, we should read the method overloading in java.

Most of the beginners have a common doubt whether it’s possible to overloading main method in java? How does work if we overload main method in java? Which method gets the call first? In this article, we will resolve all the ambiguities.

Overloading main method in java

The main() method is a special method because it’s the entry point of Java application. The JVM will always call the main method to start the application. But as we said it’s a method so like any other method, we can overload it. You can overload the main method as per the method of overloading rules. You can overload it by the number of parameters or the type of parameters or both.
Here we will see how to overloading main method in java. We will overload the method in different ways.

public class OverloadMainMethod 
{
	// It is main method with String type of parameters
	// It is entry point for JVM
	public static void main(String arg[])
	{
		System.out.println("Main method having parameter  of String type");
	}
	
	// It is overload form of main method with String type of parameters
	public static void main(String arg[], String b)
	{
		System.out.println("Main method having parameter  of String type");
	}
	
	// It is overload form of main method with int type of parameters
	public static void main(int a)
	{
		System.out.println("Main method having parameter of int type");
	}
}

Output: Main method having parameter of String type

In the above example, we have been overloading the main() method. Here we define two more methods with different types of parameters. You must have noticed the JVM calling the original main() method that is defined with  String type of parameters (String arg[]). It is not calling the overloaded main methods.

How JVM works when main() overloaded?

When the user does the action to start the application, The JVM always looks for the main method with its signature to launch the program. If the main() method is not defined with String parameters (String[] args) the JVM, not able to run it.

In above example we have overloaded the main method and defined two more main method with different signature. But the JVM execute the original main method, we can call the overloaded main method from the actual main method only. 

Overloading main method in java

Leave a Comment