Ahmed
Ahmed

Reputation: 3458

Main function in java?

Actually , I have 2 questions . The first is Why there should be a main function in a project and the second If I can have more than one main function in a single project and If that would be useful ?

Upvotes: 4

Views: 1114

Answers (5)

Gábor Lipták
Gábor Lipták

Reputation: 9776

This is a convention in java, that classes having a public static void main method having String array argument can be run from command line. The main method itself is only needed, if your program is a command line application. If it is a Java Applet, or a Java EE application, it is not needed at all. Command line arguments can be accessed as the String array argument of main method.

You can have main method for each class you have if you want. Anyway it is a best practice to have one class having main method in each project, and if you want to distribute it as an executable jar, you can define it in manifest.mf of the jar.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272237

Why should there be a main() ? Standard applications need an entry point. Other applications (e.g. web applications) are hosted in a container, and have their own entry points and lifecycle.

Can you have more than one main() ? Yes. Is that useful ? Yes. For example, you can ship one .jar file and provide different entry points via different classes/main() methods, and thus provide one means of enabling different functionality.

Upvotes: 4

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

Just to add briefly to what Boris Pavlovic said, you can have a main method in every class in your project but the usefulness of something like that is not clear.

The main method is just a method after all and there are no restrictions on having methods with the same signatures in different classes. It is up to you to decide which class in your project will be the one with the main method that starts your application running.

Upvotes: 0

Cephalopod
Cephalopod

Reputation: 15145

1) There "should" not be a main function in a project by default. Your projects needs a main function if it is intended to be executable (i.e. with java -jar myApp.jar). It should not have a main function if it is "only" a library that is used by other projects.

2) It might be usefull if a) you have a complex build process that produces multiple jars, b) you expect that for each execution of your program the main class to choose is specified via command line (I dont know the syntax, but it should be possible). For instance, you could provide your application as a single jar file with several .bat or shell scripts, each starting a different main class in the jar.

Upvotes: 1

Boris Pavlović
Boris Pavlović

Reputation: 64632

Main function serves as a bootstrapping point of your application, a starting point where the execution begins. Every class in your project can have a main method.

Upvotes: 5

Related Questions