Can there exist two main methods in a Java program?
Only by the difference in their arguments like:
public static void main(String[] args)
Yes it is possible to have two main() in the same program. For instance, if I have a class Demo1 as below. Compiling this file will generate Demo1.class file. And once you run this it will run the main() having array of String arguments by default. It won't even sniff at the main() with int argument.
class Demo1 {
static int a, b;
public static void main(int args) {
System.out.println("Using Demo1 class Main with int arg");
a =30;
b =40;
System.out.println("Product is: "+a*b);
}
public static void main(String[] args) {
System.out.println("Using Demo1 class Main with string arg");
a =10;
b =20;
System.out.println("Product is: "+a*b);
}
}
Output:
Using Demo1 class Main with string arg
Product is: 200
But if I add another class named Anonym and save the file as Anonym.java. Inside this I call the Demo1 class main()[either int argument or string argument one]. After compiling this Anonym.class file gets generated.
class Demo1 {
static int a, b;
public static void main(int args) {
System.out.println("Using Demo1 class Main with int arg");
a =30;
b =40;
System.out.println("Product is: "+a*b);
}
public static void main(String[] args) {
System.out.println("Using Demo1 class Main with string arg");
a =10;
b =20;
System.out.println("Product is: "+a*b);
}
}
class Anonym{
public static void main(String arg[])
{
Demo1.main(1);
Demo1.main(null);
}
}
Output:
Using Demo1 class Main with int arg
Product is: 1200
Using Demo1 class Main with string arg
Product is: 200