Can there exist two main methods in a Java program? Only by the difference in their arguments like:
public static void main(String[] args)
and second can be
public static void main(StringSecond[] args)
If it is possible,which Method will be used as the entry point? How to identify this? please help.
The signature of main method must be
A class can define multiple methods with the name main. The signature of these methods does not match the signature of the main method. These other methods with different signatures are not considered the "main" method.
i have check in java version 1.6.0_32 multiple main method is working but there should one main method like public static void main(String []args) of type signature. Ex is here which i had tested.
Here you can see that there are 2
public static void main (String args[])
in a single file with the nameTest.java
(specifically didn't use the name of file as either of the 2 classes names) and the 2 classes are with the default access specifier.When we compile the code Test.java it will generate 2
.class
files (vizSum.class
andDefClass.class
) and if we run Test.java we cannot run it as it won't find any main class with the name Test. Instead if we dojava Sum
orjava DefClass
both will give different outputs using differentmain()
. To use the main method of Sum class we can use the class nameSum.main(null)
orSum.main(1)//Passing integer value in the DefClass main()
.In a class scope we can have only one
public static void main (String args[])
per class since a static method of a class belongs to a class and not to its objects and is called using its class name. Even if we create multiple objects and call the same static methods using them then the instance of the static method to which these call will refer will be the same.We can also do the overloading of the main method by passing different set of arguments in the main. The Similar example is provided in the above code but by default the control flow will start with the
public static void main (String args[])
of the class file which we have invoked usingjava classname
. To invoke the main method with other set of arguments we have to explicitly call it from other classes.The answer is no; there can only one "main" method - where "main" means an entry point you can "run".
You can code overloaded versions as in your example, but they can't be "run".
There can be more than one main method in a single program. But JVM will always calls String[] argument main() method. Other method's will act as a Overloaded method. These overloaded method's we have to call explicitly.
There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method