Can we overload main() method in Java?

Here, we are going to learn, can we overload main() method in Java? Is it possible to overload main() method in Java? By Preeti Jain Last updated : January 02, 2024

Can we overload main() method in Java?

The question is that "can we overload main() method in Java?"

  • Yes, We can overload the main() method in Java.
  • JVM calls any method by its signature or in other words JVM looks signature and then call the method.
  • If we overload a main() method in a program then there will be multiple main() methods in a program. So JVM calls which method? we don't need to confuse if we have multiple main() methods then JVM calls only one main() method with (string[] argument) by default.

Example 1: Overloading main() method

class MainMethodOverloading {
    public static void main(String[] args) {
        System.out.println("We are in String[] args");
    }

    public static void main(int args) {
        System.out.println("We are in int args");
    }

    public static void main(String args) {
        System.out.println("We are in String args");
    }
}

Output

The output of the above example is:

E:\Programs>javac MainMethodOverloading.java

E:\Programs>java MainMethodOverloading
We are in String[] args

By default JVM call only one main() method of a String argument, But if we want to call another main() method or any other overloaded main() method, then we can do only one thing that is we can call overloaded main() method explicitly.

We can call other main() methods inside the original main() method with a String argument.

Example 2: Overloading main() method

// Java Program to demonstrate overloading of 
// main() method
import java.io.*;

class MainMethodOverloading {
    // Origional main() method
    public static void main(String[] args) {
        System.out.println("Hi, We are in main (String [] args) ");
        MainMethodOverloading.main("Call main() with one argument");
    }
    // These are the overloaded main() methods 
    public static void main(String args1) {
        System.out.println(args1);
        MainMethodOverloading.main("call main() with", "two argument");
    }
    public static void main(String args1, String args2) {
        System.out.println(args1 + args2);
        MainMethodOverloading.main("call main() with", "three argument", "from two argument main()");
    }
    public static void main(String args1, String args2, String args3) {
        System.out.println(args1 + args2 + args3);
    }
}

Output

The output of the above example is:

E:\Programs>javac MainMethodOverloading.java

E:\Programs>java MainMethodOverloading
Hi, We are in main (String [] args) 
Call main() with one argument
call main() withtwo argument
call main() withthree argumentfrom two argument main()

Comments and Discussions!

Load comments ↻






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