Can we Overload the main() method in Java?

One of the common doubts among Java beginners while learning to overload and overriding is, whether it’s possible to overload main() in Java? Can you overload the main() method in Java? How will JVM find if you change the signature of the main method as part of the method overloading? etc.

So, the answer is Yes, We can overload the main() method in java but JVM only calls the original main method, it will never call our overloaded main method.

Overload Main() Method in Java.

This is just one way, you can create as many versions of main as you want, but you must make sure that the method signature of each main is different. You can change the method signature by changing the type of argument, number of arguments or order of arguments. Best practice to overload a method is by changing the number of arguments, or types of arguments. In Java, it’s not possible to overload the method by just changing return type.

Example:-

public class Maxester { 


// Overloaded main method 1  
    // Should be executed when character is passed 
    public static void main(char value) 
    { 
        System.out.println("Inside main(char value) method"); 
    } 
  
    // Overloaded main method 2 
   // Should be executed when int value is passed 
    public static void main(int value) 
    { 
        System.out.println("Inside main(int value) method"); 
    } 
    // Overloaded main method 3  
    // Should be executed when double value is passed 
    public static void main(Double[] value) 
    { 
        System.out.println("Inside main(Double[] value) method"); 
    } 
  
    // Original main() 
    public static void main(String[] args) 
    { 
        System.out.println("Inside original main(String[] args) method "); 
    } 
} 

Output:-

Inside original main(Strings[] args) method.

As from the above example, it is clear that every time the original main method executes but not the overloaded methods because JVM only executes the original main method by default but not the overloaded one.

we can overload the main() method in java
But, to execute overloaded methods of main, we must call them from the original main method.

I hope this will be helpful to you.

Thank you.

One thought on “Can we Overload the main() method in Java?

Leave a Reply

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