Can I have multiple main methods in the same class?
By admin on Jul 31, 2007 in JAVA Interview Questions
No the program fails to compile. The compiler says that the main method is already defined in the class.
Java Interview Questions | IT interview questions | Software Testing Interview questions | .Net Interview Questions | Job Interview Questions & Answers | Tough Interview Questions | Technology Interview Questions | Tech Interview Questions | Testing Interview Questions | SAP Interview Questions | ABAP Interview Questions | Data Warehousing Interview Questions
Current ArticleBy admin on Jul 31, 2007 in JAVA Interview Questions
No the program fails to compile. The compiler says that the main method is already defined in the class.
2 Comment(s)
By Anshul on Feb 3, 2008 | Reply
No the above given answer is wrong.
A class can have many main methods provided they are overloaded ie having the same name as main but different arguments.
And the compiler will successfully compile this program and also run the program using the main having the argument as String and leave the other mains as useless untill the main having String as arguments is calling the other mains which act as functions.
By Niti on Aug 12, 2008 | Reply
A class can have multiple main methods provided that they all have different arguments in terms of number and type.
Program will compile successfully and at run time JVM will execute the main in which array of String has been passed as argument.We can call other methods from this main.
for example-
class Multiple_main
{
public static void main(String a[])
{
System.out.println(”Main 1″);
main();
}
public static void main()
{
System.out.println(”Main 2″);
main(3);
}
static void main(int a)
{
System.out.println(”Main 3—–” + a);
}
}