Yes, we can overload main() method. A Java class can have any number of main() methods. But it should have one main() method with signature as “public static void main(String[] args)” to run. If not class will compile but not run.
Example
/**
* This class is used for main method overloading.
* @author w3schools
*/
public class MainMethodOverloding {
//overloaded main method with one parm
public static void main(int num1){
System.out.println(num1);
}
//overloaded main method with two parm
public static void main(int num1, int num2){
System.out.println(num1 + num2);
}
public static void main(String args[]){
//method call
main(20);
main(10, 20);
}
} |
/**
* This class is used for main method overloading.
* @author w3schools
*/
public class MainMethodOverloding {
//overloaded main method with one parm
public static void main(int num1){
System.out.println(num1);
}
//overloaded main method with two parm
public static void main(int num1, int num2){
System.out.println(num1 + num2);
}
public static void main(String args[]){
//method call
main(20);
main(10, 20);
}
}
Output
Java interview questions on main method