Tuesday, 17 October 2017

Can we overload main() in java?


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

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

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

Source FileMainOverloading.java 

package basic;

public class MainOverloading {

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

      }
     
      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:
Overloaded methods will not be executed here 

---------------------------------------------------------------------------------------------------

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. 

Given below is modified version of above code snippet. Here overloaded main() is executed. Have a look,
---------------------------------------------------------------------------------------------------

Source FileMainOverloading.java 

package basic;

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 aint 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 aint b) 
b=54

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.