Java program to overload main() method

Learn how to overload main() method in Java?
Submitted by Nidhi, on March 22, 2022

Problem Solution:

In this program, we will overload the main() method by creating 3 methods with a different number of arguments.

Program/Source Code:

The source code to overload the main() method is given below. The given program is compiled and executed successfully.

// Java program to overload main() method

public class Main {
  public static void main(int num) {
    System.out.println("Method with integer argument: " + num);
  }

  public static void main(String str) {
    System.out.println("Method with String argument: " + str);
  }

  public static void main(String[] args) {
    System.out.println("Method with String[] argument.");

    main(10);
    main("Hello");
  }
}

Output:

Method with String[] argument.
Method with integer argument: 10
Method with String argument: Hello

Explanation:

In the above program, we created a Main class that contains 3 overloaded main() methods with a specified different number of arguments. Here, method with string[] argument is an entry point for the program, here we called the overloaded method and printed the result.

Java Method Overloading Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.