In this post, we will see about "Can we overload main method in java".This is one of the most asked Core java interview questions.
Yes, we can overload main method in java but when you run your program, JVM will search for public static void main(String[] args) and execute that method.
Overload main method in java
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; public class OverloadTestMain { public static void main(String[] args) { System.out.println("Inside main(String[] args)"); } public static void main(Integer arg1) { System.out.println("Inside main(Integer arg1)"); } public static void main(Integer[] arr) { System.out.println("Inside main(Integer array)"); } } |
When you run above program, you will get below output.
As you can see, we have overloaded main method but still, JVM calls the method with signature public static void main(String[] args).
Please note that JVM considers var args public static void main(String…args) same as public static void main(String[] args).
If you want to call overloaded method, then you need to call it from main method with signatute public static void main(String[] args).
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class OverloadTestMain { public static void main(String[] args) { System.out.println("Inside main(String[] args)"); main(2); main(new Integer[] {1,2,3}); } public static void main(Integer args) { System.out.println("Inside main(Integer args)"); } public static void main(Integer[] arr) { System.out.println("Inside main(Integer arr)"); } } |
When you run above program, you will get below output.
Inside main(Integer args)
Inside main(Integer arr)
As you can see, we have called the overloaded methods from main method with String[] args.
That’s all about "Can we overload main method in java".
You can go through other interview questions about method overloading and method overriding.