Previous | Next | Trail Map | Writing Java Programs | Table of Contents


Command Line Arguments

Your Java application can accept any number of arguments from the command line. Command line arguments allow the user to affect the operation of an application. For example, a program might allow the user to specify verbose mode--that is, specify that the application display a lot of trace information--with the command line argument -verbose.

When invoking an application, the user types the command line arguments after the application name. For example, suppose you had a Java application, called Sort, that sorted lines in a file, and that the data you want sorted is in a file named ListOfFriends. If you were using DOS, you would invoke the Sort application on your data file like this:

C:\> java Sort ListOfFriends
In the Java language, when you invoke an application, the runtime system passes the command line arguments to the application's main method via an array of Strings. Each String in the array contains one of the command line arguments. In the previous example, the command line arguments passed to the Sort application is an array that contains a single string: "ListOfFriends".

Echo Command Line Arguments

This simple application displays each of its command line arguments on a line by itself:
class Echo {
    public static void main (String args[]) {
        for (int i = 0; i < args.length; i++)
            System.out.println(args[i]);
    }
}
Try this: Invoke the Echo application with the command line shown in this DOS example:
C:\> java Echo Drink Hot Java
Drink
Hot
Java
You'll notice that the application displays each word--Drink, Hot, and Java--on a line by itself. This is because The Space Character Separates Command Line Arguments.

Conventions

There are several conventions that you should observe when accepting and processing command line arguments with a Java application.

Parsing Command Line Arguments

Most programs accept several command line arguments that allow the user to affect the execution of the application. For example, the UNIX command that prints the contents of a directory--the ls utility program--accepts arguments that determine which file attributes to print and the order in which the files are listed. Typically, the user can specify the command line arguments in any order thereby requiring the application to parse them.

Note to C and C++ Programmers: The command line arguments passed to a Java application differ in number and in type than those passed to a C or C++ program. For further information refer to Java Command Line Arguments Differ from C and C++ .
Note to Applet Programmers: The runtime system only passes command line arguments to Java applications--applets use parameters instead. For more information about applet parameters, see Communicating With the User .


Previous | Next | Trail Map | Writing Java Programs | Table of Contents