As a part of Java Interview Questions, in this post, we will see a frequently asked interview question “Can we overload main method in Java?“.
When we keep more than one methods in a class with same method name but at least with one difference in its method signature (Number of arguments , Order of arguments and Type of arguments), is called as Method Overloading.
Note:- No return type is considered in overloading.
So can we overload main method in Java? Answer is Yes, We can.
Execution of a Java program starts from main() method. In fact we should say that Execution of a Java program starts from a main() method whose actual syntax is “public static void main(String[] args)”.
We can write multiple valid overloaded main method in a class but JVM always looks for a main method with syntax as “public static void main(String[] args)“. If it finds , it will start execution from there otherwise will give error stating “Error: Could not find or load main“.
Programming Example:-
package Concepts; public class OverloadedMainMethod { // Overloaded main method public static void main(String str) { System.out.println("public static void main(String str)"); } // Overloaded main method public static int main(int str) { System.out.println("public static void main(String str)"); return 1; } // Overloaded main method public void main(String str, int val) { System.out.println("public void main(String str, int val)"); } // Main method from where execution starts public static void main(String[] args) { System.out.println("public static void main(String[] args)"); // Calling other main method main("Amod"); main(10); new OverloadedMainMethod().main("Amod", 10); } }
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning
You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.