Where should I put the public static void main (String [] args)?

I do not think that this affects the output of the program, but which class should I put

public static void main(String[] args) { //... } 

in my program? Is it better to form a separate class or put it in a class that does something else? If I have to put it in a class that will do something else, which one? Does it matter? This is actually just a conventional thing. Usually I create a separate class or put it in a class that deals with gui, but I would like to know the correct way to execute it.

+7
java conventions
source share
3 answers

If you write very short programs (for example, simple algorithms), it may seem more convenient to simply add your main method to a class containing some basic program logic. However, for large projects, it is very useful to separate your main method from business logic / database access / everything else, which should work as an encapsulated object.

The main method should simply give you the beginning of the chain so that you can easily follow the workflow of your program from the very beginning. Enabling logic (even simple number / string conversions) in a class containing the main method can lead to unnecessary chaos, try to separate everything that you really don't need, and put it in helper classes.

+3
source share

When you write a program with several classes, then the main() method must be in the class with the name of the program.

If the program name is temp.java , and there are two classes named temp and temp1 , the main() method must be included in the class. No separate class needed

+1
source share

The right way to handle this depends on your application. But in most cases, it is best to have very simple and understandable code in your main method that reflects the behavior of your application in a very broad sense.

0
source share

All Articles