When you use a command shell to run your Java program, you first type the command "java" on the command line. This is followed by any run-time options you want to use and the name of the java class that contains your main routine. Instead of immediately hitting 'enter', you can type other items on this line (where white space is used to separate these items). These other items are the command line parameters for this particular execution of your program. They can be followed redirection expressions if you want to redirect input and/or output. Note that redirection expressions are not command line arguments. Command line arguments must, if fact, precede any redirection expressions.
Example:Command line arguments are an easy way to add some versatility to your programs. You can, for instance, pass in the names of input and output files as command line parameters instead of hard-coding those names into your program (and you should have a hard-coded default name in your program, just in case no command line arguments are provided). You can pass numbers to specify how many times a loop is to be executed, etc. In many cases, this allows you to test your program under a variety of circumstances with having to edit and re-compile your code.
java -Xms 2g program1 abc xyz 23423.5 < readme.txt >2 errmsg.txt > stdout.txt
runs program1.class with 3 command line parameters, namely "abc", "xyz" and "23423.5"
The command line parameters are passed to the main method as an array of strings. This is the
parameter you are accustomed to coding in the signature of your main method
Example:If you are not the main method (e.g. if you are the run() method of an applet), then you can't access the command line arguments unless the main method passes them to you in some way.
public static void main (String [] cmdlineargs) { …}
gives the name cmdlineargs to the array of command line parameters. In this case, the number of command line parameters is cmdlineargs.length (which could be zero) and the arguments themselves are cmdlineargs[0], cmdlineargs[1], etc. You should be careful to determine the number of command line arguments before you try to access any of them to avoid throwing an IndexOutOfBounds exception.
No. Your command line parameters are Strings. Some of those strings, however, could consist of the characters '0', '1', '2', '3', '4', '5', '6', '7', '8' and '9' and possibly a decimal point '.'. In that case, you can convert the string to a numerical value. The easiest way to do this is to use the wrapper class static methods Integer.parseInt(…), Double.parseDouble(…), etc.
| Things to try |
|---|
|
© Wiggen & Associates, 2007