Can we overload a main()
method in Java?
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)
This is perfectly legal:
public static void main(String[] args) {
}
public static void main(String argv) {
System.out.println("hello");
}
Yes According to my point of view, we are able to overload the main method but method overloading that's it. For Example
class main_overload {
public static void main(int a) {
System.out.println(a);
}
public static void main(String args[]) {
System.out.println("That's My Main Function");
main(100);
}
}
In This Double Back slash Step, I am just calling the main method....
Yes you can Overload main method but in any class there should be only one method with signature public static void main(string args[])
where your application starts Execution, as we know in any language Execution starts from Main method.
package rh1;
public class someClass
{
public static void main(String... args)
{
System.out.println("Hello world");
main("d");
main(10);
}
public static void main(int s)
{
System.out.println("Beautiful world");
}
public static void main(String s)
{
System.out.println("Bye world");
}
}
Yes a main method can be overloaded as other functions can be overloaded.One thing needs to be taken care is that there should be atleast one main function with "String args[] " as arguments .And there can be any number of main functions in your program with different arguments and functionality.Lets understand through a simple example:
Class A{
public static void main(String[] args)
{
System.out.println("This is the main function ");
A object= new A();
object.main("Hi this is overloaded function");//Calling the main function
}
public static void main(String argu) //duplicate main function
{
System.out.println("main(String argu)");
}
}
Output:
This is the main function
Hi this is overloaded function
YES, you can overload main()
But to be clear -- although you can overload main, only the version with the standard signature will be executable as an application from the command line. e.g
public static void main(String a,String... args){
// some code
}
2)public static void main(String[] args){//JVM will call this method to start
// some code
}