Can We Overload The Main Method In Java?


Answer :

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:

public class Test {     public static void main(String[] args) {         System.out.println("main(String[] args)");     }      public static void main(String arg1) {         System.out.println("main(String arg1)");     }      public static void main(String arg1, String arg2) {         System.out.println("main(String arg1, String arg2)");     } } 

That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.

You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

EDIT: Note that you can use a varargs signature, as that's equivalent from a JVM standpoint:

public static void main(String... args) 

Yes, you can overload main method in Java. But the program doesn't execute the overloaded main method when you run your program, you have to call the overloaded main method from the actual main method.

that means main method acts as an entry point for the java interpreter to start the execute of the application. where as a loaded main need to be called from main.


Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:

class Simple{     public static void main(int a){     System.out.println(a);     }      public static void main(String args[]){     System.out.println("main() method invoked");     main(10);     }   }   

It will give the following output:

main() method invoked 10 

Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?