user5814491
user5814491

Reputation: 11

Two classes with main methods, which will be executed first?

I have two classes in an application and both have main methods ,when application is executed which class's main method will be executed first ?

Upvotes: 1

Views: 103

Answers (2)

Jiri Tousek
Jiri Tousek

Reputation: 12450

Short answer: Neither will be called first, because there's no magic executing them. You decide which one you call.


That a class has a main(String...) method merely means it can be used as the application's entry point (i.e. the place where execution starts), not that by some "magic" every such method will be executed.

Once you have a main method, you can call it using:

java path.to.my.Class

Alternatively, if you package your application in a jar file, you may indicate in its manifest which class (and thus which main method) shall be used as the entry point.

Therefore, either way it's up to you to indicate which main method to call.

Upvotes: 0

Arnaud
Arnaud

Reputation: 17534

It's up to you to specify which class you call as the main one.

java com.mypackage.MyMainClass

Or if you have a runnable jar, the META-INF/manifest.mf in the jar indicates which is the main class, like :

Main-Class: com.mypackage.MyMainClass

Now this command will call the declared main class in the jar.

java -jar myjar.jar

For more details, see : Setting an Application's Entry Point

Upvotes: 1

Related Questions