Can we overload main method in java

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:

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.

Inside main(String[] args)

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:

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(String[] args)
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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.