Wednesday, May 14, 2008

Explain the signature of the main method

public static void main(String [] args) – this is the signature of the main method in Java. ‘public’ access specifier means that the method can be called from outside. This is the first method to be called by the JRE to start the execution, so it needs to be declared ‘public’.

static’ means that it’s a Class method and not an instance method. Since, this method is called to start the execution, so we can’t have it as an instance method. Unless you start the execution, how will you create an instance? So, we must declare this as a ‘static’ method.

void’ means that the method returns nothing. The designers of Java thought that the main method should not return anything and hence they made it mandatory to declare the return type as ‘void’. It could have been ‘int’ as is the case in C language. But, this hardly adds any value. In C, a return value of ‘0’ specifies successful completion of the program, but in Java we have a far better and rich Exception Handling mechanism, so we don’t really need to rely on the return value of the main method.

String[] args’ this represents the command line arguments passed. All the arguments are stored in a String array and you need to type-cast it accordingly before using in the program. This array is also 0-indexed and the first argument is stored in args[0].

Note: you can overload the main method and can have any number of main methods of other signatures, but the JRE will automatically start the execution by calling only the main method which is having the above discussed signature. If the JRE doesn’t find any such main method, then it’ll raise an appropriate exception. FYI - It’s not a good idea to have the main method overloaded. You probably need to check your design before doing this.


1 comment:

JE @ code review guide said...

You put in a lot of details for each specifier used with the main method. Thanks for that.
For rest of the concepts associated with main method, readers can refer my notes on main method