Wednesday 5 December 2012

Why main() has string array as a parameter?

Leave a Comment

The JVM is looking for a very special main method to run. Only the signature for command line input-
public static void main( String[] args )
is found. All other methods with name main are just "normal" methods.
It's still a valid method. For example, you could have a static method called "main" with an int parameter if you wanted:
public static void main(int foo){}

The compiler doesn't complain because it's a valid method! It's just that, in order to run a Java program, Java looks for a static method called "main" with a single String array argument.

Not every class has to have a public static void main(String[] args) method, only the one you want to run from the JVM. The result is that your class will compile with no error if it finds public static void main() but will throw an exception if you try and run it with the JVM because it can not find the entry point of the program.
Bottom line the entry point of your program must be public static void main(String[] args)which must be located in at least one of your .java files.
Note you can have multiple public static void main(String[] args) methods in your code (one per class) the advantage is you can use these to test and debug your classes individually.
Java supports method overloading. This means you can have several methods with the same name, but different arguments.
Having said that, when you run java ClassName, Java looks in ClassName.class for a method with the signature public static void main (String[]) (it doesn't care what the String[] variable is named) and runs it. If it doesn't find one, Java will bomb out with the following exception:



0 comments:

Post a Comment