xhtml
 

Command Line Arguments

Command lines provide a simple way of giving input data to a program. We know already that a Java program is run with a command such as java Program. You can pass arguments to the program by adding them to the command line like this:

java Program arg0 arg1 ...

For example, suppose there is a program ToHtml which converts a plain text file into a Web page. The program might have two arguments which give the name of the input file and the name of the output file like this:

java ToHtml document.txt document.html

In Java, the main method is always declared like this:

public static void main(String[] args)

The main method has one argument called args which is an array of the argument strings from the command line. The number of arguments in the array is args.length, which might be zero if there aren't any arguments. In the case of the ToHtml program, args.length is 2, the name of the input file is in args[0] and the name of the output file is in args[1]. The reason why the items in the array args are numbered from 0 will be explained when we cover arrays later on.


Back