The main function in java?

Actually, I have 2 questions. Firstly, why should there be a main function in a project, and the second If I can have more than one main function in one project, and if it would be useful?

+4
source share
5 answers

Why should there be main() ? Standard applications need an entry point. Other applications (such as web applications) are hosted in a container and have their own entry points and life cycle.

Can you have more than one main() ? Yes. This is useful? Yes. For example, you can send a single .jar file and provide different entry points using different class / main() methods and thus provide one way to provide different functionality.

+4
source

The main function serves as the loading point of your application, the starting point where execution begins. Each class in your project can have a main method.

+5
source

1) "Default" should not be the main function in the project. Your projects require a basic function if it is intended to be executed (i.e., with java -jar myApp.jar). It should not have a core function if it is "only" a library that is used by other projects.

2) It can be useful if: a) you have a complex build process that creates several cans, b) you expect that for each execution of your program the main class to be selected is set using the command line (I don’t know the syntax, but it should be possible). For example, you can provide your application as a single jar file with several .bat or shell scripts, each of which runs a different main class in the bank.

+1
source

To briefly talk about what Boris Pavlovich said, you may have a basic method in each class of your project, but the usefulness of something like this is not clear.

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

0
source

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

You can have a main method for each class if you want. In any case, it is best to have one class that has the main method in each project, and if you want to distribute it as an executable ATM , you can define it in the manifest .mf jars.

0
source

All Articles