Julius Randle Jersey  Allen Iverson Jersey  Can we overload main() in java? – Ilyas Blog

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);
      public static void main(int a, int b){
            System.out.println(“a=”+ a);
            System.out.println(“b=”+ b);

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){
      public static void main(int aint b){

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

You may also like to read:

  • ArrayList vs LinkedList
  • ArrayList vs Vector
  • Collection vs Collections
  • ArrayList vs HashSet
  • Iterator vs Enumeration
  • Java Mini Projects

Source link

Can we overload main() in java?

Leave a Reply

Your email address will not be published. Required fields are marked *