This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
RE:Arguments in main
Posted by Kishori Sharan on February 10, 2001 at 11:11 AM
When you run your class then you can also pass some parameters to the class you want to run. Since the execution starts in main methods those arguments specified by you at command line are passed to main method. Suppose you type java C1 where C1 is your class you want to run then main method of C1 is called. Since you ddidn't pass any parameter after C1 on command line then JVM will just ccreate an empty string array like String[] temp = new String[0] ; and then it makes a call like C1.main ( temp ) ; // Internally it uses reflection to do this If you pass any parameter at command line then java C1 param1 param2 then JVM stores these param1 and param2 in string array passes them to main method of class C1. Some language uses a String argument instead of String array and in those cases you have to parse the command line parameters. Now your question is why "String[] params" is compulsory in main declaration. Let us take a case when it is not necessary in j ava. In that case you would have to define at least two main methods in a class if you want to run it. One which will be called when you don't pass any parameters and the other when you pass some parameters. And your both main methods would have been identical. To make the programming lilfe easier and to reduce the confusion which main will be called when Java insists to define you a main method with "String[] params" argument and this method will be called when you run your class irrespective of no of parameters you pass. Thanx Kishori
Replies:
|