Previous | Next | Trail Map | Writing Java Programs | Command Line Arguments


Conventions for Command Line Arguments

The Java language follows UNIX conventions that define three different types of command line arguments: In addition, your application should observe the following conventions that apply to Java command line arguments.

Word Arguments

Arguments, such as -verbose, are word arguments and must be specified in their entirety on the command line. For example, -ver would not match -verbose.

You can use a statement such as the following to check for word arguments.

if (argument.equals("-verbose"))
    vflag = true;
The statement checks for the word argument -verbose and sets a flag within the program indicating that the program should run in verbose mode.

Arguments that Require Arguments

Some arguments require more information. For example, a command line argument such as -output might allow the user to redirect the output of the program. However, the -output option alone does not provide enough information to the application: how does the application know where to redirect its output? Thus, the user must also specify a filename. Typically, the next item on the command line provides the additional information for command line arguments that require it. You can use a statement such as the following to parse arguments that require arguments.
if (argument.equals("-output")) {
    if (nextarg < args.length)
        outputfile = args[nextarg++];
    else
        System.err.println("-output requires a filename");
}
Notice that the code snippet checks to make sure that the user actually specified a next argument before trying to use it.

Flags

Flags are single character codes that modify the behaviour of the program in some way. For example, the -t flag provided to UNIX's ls command indicates that the output should be sorted by time stamp. Most applications allow users to specify flags separately in any order:
-x -n     or    -n -x
In addition, to make life easier for users, applications should also allow users to concatenate flags and specify them in any order:
-nx    or    -xn
The sample program described on the next page implements a simple algorithm to process flag arguments that can be specified in any order and/or separately.


Previous | Next | Trail Map | Writing Java Programs | Command Line Arguments