Site icon TestingDocs.com

Can a Java class have multiple main methods?

The answer to the question would be Yes. We can have multiple methods with the same name main in a class. But the caveat is that there should be only one main method with the following signature

public static void main(String[] args)

or

public static void main(String… args)

 

JVM looks for main with these signatures and ignores the other methods with the name main in the class. The sample code snippet is shown below with multiple main methods in a class.

In case you are attending an interview, the same question can be asked differently as: Can we overload the main method?

The answer to the question would be Yes. We can overload the main method. We can create many methods with the same name main. However, as mentioned earlier, only the public static void main(String[] args) method is used for the program execution. The sample program below has different main method signatures.

Sample code snippet:

public class RunConfigurationDemo {
 
 public static void main(String... args)
 {
 System.out.println(args[0]);
 }
 
 public static void main(String args)
 {
 System.out.println(args);
 }
 
 public static void main(int args)
 {
 System.out.println(args);
 }

}

 

Passing the arguments to the application:

We can pass arguments to the Java application as shown in the below steps:

Launch run configurations Run >> Run Configurations

Alternatively, right-click on the program Run as >> Run configurations…

Choose the Java application >> Arguments

We can pass program arguments and VM arguments to the application program.

 

 

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version