July 7, 2014
Understand the main method of a Java class
The main method is the start point of any Java executable application. It has the signature :
1 2 3 |
public static void main(String args[]) { // a lot of code here } |
or,
1 |
public static void main(String... args) { /* a lot of code here */ } |
The following rules apply when creating the main method :
- The main method must be marked as public and static. The order in which public and static may appear doesn’t matter;
- The name of the main method must be main;
- The return type of the main method must be void;
- The method argument must be an array of Strings or a variable argument of type String (i.e., varargs).
NOTE : The elipsis (i.e., …) must follow the type of the variable, and not the variable itself.
Observations :
- It is not mandatory for the name of the variable passed to the main method to be args. It can be any valid Java Identifier;
- In case you are use an array of Strings as parameter, the square brackets, [], either the type of the variable or its name;
- The order of the keywords, public and static can be changed (i.e., use static public instead of public static).
NOTE : The main method is a static method and for this reason only static members are accessible from the main method More there is no this available to main method.