can we overload main() method in java?

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

Please follow and like us:
Content Protection by DMCA.com