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 W3spoint */ 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
20 30 |
Java interview questions on main method
- Can we overload main() method in java?
- Can we declare main() method as private or protected or with no access modifier?
- Can we declare main method as non static in java?
- Why main() method must be static?
- Can we change return type of main() method?
- Can we run java class without main() method?
- Can we declare the main method as final?
Please follow and like us: