Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I don't think it has any effect on the program output, but what class should I put the

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

method in my program? Is it better form to create a separate class, or put it in a class that does something else? If I should put it in a class that does something else, which one? Does it matter? This is really just a conventions thing. Normally I create a separate class or put it in the class that deals with the gui, but I would like to know the right way of doing it.

like image 373
Zac Avatar asked Jun 07 '14 13:06

Zac


People also ask

Where should the static main () method be located in your class?

Main method should just give you the beginning of the chain, so that you could easily follow the workflow of your program from the very beginning.

Can we write static public void main String [] args?

Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice.

Where can we write main method in Java?

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs . Also String array argument can be written as String...

What is the used of public static void main String [] args in Java program?

It is a keyword and is used to specify that a method doesn't return anything. As the main() method doesn't return anything, its return type is void. As soon as the main() method terminates, the java program terminates too.


1 Answers

If you are writing very short programs (e.g. simple algorithms), it may seem to be more convenient to just add your main method to the class containing some basic program logic. However, for greater projects it is very helpful to separate your main method from business logic/database access/anything else that should be working as an encapsulated entity.

Main method should just give you the beginning of the chain, so that you could easily follow the workflow of your program from the very beginning. Including logic (even simple number conversion/string operations) in class containing main method could cause some unnecessary chaos, try to separate everything what you don't really need there and put it in helper classes.

like image 155
TheMP Avatar answered Sep 30 '22 14:09

TheMP