Articles

Can main method be overloaded in java?

Can main method be overloaded in java?


Yes, the main() method can be overloaded in java programs.

Given below is the sample code snippet where main() method has been overloaded twice. If you want you can experiment by overloading more main() methods as per your choice and requirement.

To prove our point that main() can be overloaded, below java code is sufficient.

Lets look at given code:

public class MainOverloading {

      public static void main(String[] args) {
            System.out.println("Overloaded methods will not be executed here");

      }
     //main overloaded
      public static void main(int x){
            System.out.println("x="+ x);
            main(5,54);
      }
     //main overloaded
      public static void main(int a, int b){
            System.out.println("a="+ a);
            System.out.println("b="+ b);
      }

}

OUTPUT

Overloaded methods will not be executed here

 

If we execute the above code, it will compile and return above output.

 

In the above code snippet JVM searches for public static void main(String[] args) type signature as regular. And anything inside public static void main(String[] args)  will be executed first. So if you want your overloaded main() method to get executed, you need to call it from inside actual main() which is entry point for all java program. 

Now we will modify above code to allow the overloaded main get called.

public class MainOverloading {

      public static void main(String[] args) {
        main(1);       //calling overloaded main

      }
     
      public static void main(int x){
            System.out.println("x="+ x);
            main(5,54);
      }
     
      public static void main(int a, int b){
            System.out.println("a="+ a);
            System.out.println("b="+ b);
      }

}

OUTPUT

x=1    //output of main(int x)
a=5    //output of main(int a, int b) 
b=54

 

This concludes that main() method can be overloaded in java.


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sonu Pandit
I am editor in chief at tutorialsinhand.com responsible for managing, reviewing and sending articles/contents for final approval to get published. Connect with me@https://www.linkedin.com/in/sonu-pandit-a77b471ab/. Join write4us program & share your skill
Page Views :    Published Date : Jul 05,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!