Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple main() methods in java

Tags:

java

methods

main

I was wondering what the effect of creating extra main methods would do to your code.

For example,

public class TestClass {
    public static void main (String[] args){
        TestClass foo = new TestClass();
    }
}

After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?

like image 858
guy8214 Avatar asked Jan 20 '11 23:01

guy8214


People also ask

Can I have multiple Main () methods in the same class?

Answer. Yes. You can have multiple methods with name main in the same class. But there should be only one main method with the signature public static void main(String[] args).

Can we have 2 main methods?

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.

Can we have multiple main methods in spring boot?

AFAIK, the best you can do is to tell Spring Boot which of the main classes in your codebase to make the main for the JAR. So your testing methodology would be implemented by editing the POM file, or by creating a separate module / POM for each of your on-the-fly tests.


1 Answers

It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like

>java TestClass

However, doing something like:

public class TestClass
{
 public static void main (String[] args)
 {
  TestClass foo = new TestClass();
  foo.main(args);
 }
}

Or

public class TestClass
{
 public TestClass()
 {
   //This gets executed when you create an instance of TestClass
   main(null);
 }

 public static void main (String[] args)
 {
  TestClass foo = new TestClass();
 }
}

That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....

When in doubt, just test it out :-)

like image 95
Zach L Avatar answered Sep 28 '22 18:09

Zach L