How to overload main method in Java

How to overload main method in Java:

We can overload the main method in Java. We can create other main methods with different arguments. The only thing is that JVM will always call the public static void main(String[] args) method.

In this post, we will learn how to overload main method in Java with an example.

Example program:

Let’s take a look at the below program:

class MyClass {
    public static void main(String[] args) {
        System.out.println("Default main");
    }

    public static void main(int intArg) {
        System.out.println("main with Integer argument");
    }

    public static void main(String strArg) {
        System.out.println("main with String argument");
    }
}

If you run the above program, it will print the below output:

Default main

Here,

  • we have three main methods.
  • If you run this, it will print Default main, i.e. it will call the default main method.

We can’t call the other overloading methods. If you want to call them, you need to call them from the default main method.

Call other main methods:

Let’s take a look at the below program:

class MyClass {
    public static void main(String[] args) {
        System.out.println("Default main");
        main(10);
        main("Hello");
    }

    public static void main(int intArg) {
        System.out.println("main with Integer argument");
    }

    public static void main(String strArg) {
        System.out.println("main with String argument");
    }
}

This will call the other main methods. If you run this, it will print the below output:

Default main
main with Integer argument
main with String argument

As you can see here, the other main methods are called from the first one.

You might also like: