Main method in Java is the point from where the program starts executing.
- In Java, the program structure should contain a class and a main method to run the program.
CLASSES AND MAIN METHOD IN JAVA:
While at least one class
should include the main method, it is optional for other classes.
What are the classes that can have the main method as an option?
- For instance, assume that there are four classes: class A, class B, class C, and class D.
- Class D has the main method. Inside class D, we can create all the objects for classes A, B, and C. (without the main method).
- However, to run or execute any program, it is mandatory to include the main method.
How to declare the main method?
Method prototype or the syntax of the main method in Java includes
public static void main(String[] args)
I) Public:
- The public is an access specifier that allows JVM to access the main() method.
II) Static
- Static is the modifier.
- By including Static, the main method can execute first because all static members have higher precedence in execution.
III) Void
- Void is the return type.
- It is essential because every method should have a return type.
- Void is used because the main method should not return value, or it may lead to a memory leak.
IV) main(String[] args):
- Main is the method name.
- (String[]) args can help store arguments.
- By writing string args, the main method can pass any number of arguments.
- Importantly, string allows to take of any alphanumeric values.