[ Team LiB ] Previous Section Next Section

1.4 Using Command-Line Arguments

As we've seen, every standalone Java program must declare a method with exactly the following signature:

public static void main(String[  ] args)

This signature says that an array of strings is passed to the main( ) method. What are these strings, and where do they come from? The args array contains any arguments passed to the Java interpreter on the command line, following the name of the class to be run. Example 1-4 shows a program, Echo, that reads these arguments and prints them back out. For example, you can invoke the program this way:

% java je3.basics.Echo this is a test

The program responds:

this is a test

In this case, the args array has a length of four. The first element in the array, args[0], is the string "this", and the last element of the array, args[3], is "test". As you can see, Java arrays begin with element 0. If you are coming from a language that uses one-based arrays, this can take quite a bit of getting used to. In particular, you must remember that if the length of an array a is n, the last element in the array is a[n-1]. You can determine the length of an array by appending .length to its name, as shown in Example 1-4.

This example also demonstrates the use of a while loop. A while loop is a simpler form of the for loop; it requires you to do your own initialization and update of the loop counter variable. Most for loops can be rewritten as a while loop, but the compact syntax of the for loop makes it the more commonly used statement. A for loop would have been perfectly acceptable, and even preferable, in this example.

Example 1-4. Echo.java
package je3.basics;

 * This program prints out all its command-line arguments.
public class Echo {
    public static void main(String[  ] args) {
        int i = 0;                           // Initialize the loop variable
        while(i < args.length) {             // Loop until the end of array
            System.out.print(args[i] + " "); // Print each argument out
            i++;                             // Increment the loop variable
        System.out.println( );                // Terminate the line
    [ Team LiB ] Previous Section Next Section