Java Overload Main Method


Java Overload Main Method

Summary: It is a frequent asked interview question. Your answer is YES and is explained in simple terms in this tutorial "Java Overload Main Method".

Method overloading is nothing but using the same method in the same class a number of times with different parameters. Just like any other method, the main() method also can be overloaded. Following program llustrates.

Program with main() overloading

public class Demo
{
  public static void main()
  {
    System.out.println("Hello World");
  }  
  public static void main(int x)
  {
    System.out.println(x);
  }
  public static void main(String args)   // observe, no [ ]
  {                                // it is simply a string and not array
    System.out.println(args);
  }
  public static void main(String args[])
  {
    main();
    main(10);
    main("way2java");
  }
}


Java Overload Main Method
Output screen of Demo.java of Java Overload Main Method

The JVM does not find ambiguity to call which main() method is to be called. It knows clearly, it requires such main() that includes the parameter String args[]. Other main() methods are treated as user-defined. As all the main() methods are static in the above code, they are called without the help of an object.

2 thoughts on “Java Overload Main Method”

  1. How JVM know that its has to call main() method having argument with array of string.
    means why JVM calls this “public static void main(String args[])” as a starting point of program. and not any other main method.

Leave a Comment

Your email address will not be published.