Accepting Command Line Arguments

Many applications require the computer to to accept any number of command line arguments.
Java allows us to enter as many command line arguments as we want and places them in an array called arg[].

The following program will loop through all given arguments and print them out.

A discussion of Java classes, methods, objects and properties will occur later in the tutorial but the args.length is an interesting example of how java works. We are referring to the args object (the command line parameters) and using the length attribute ( the # of arguments set by the interpreter at run time) to control this loop. Until we learn more about Java classes, we can simply think of args.length as a function that returns the number of command line arguments.

 

Copy the following code into a text editor and
save it as showargs.java.

class showargs {
public static void main (String args[]){
  int x;
     for (x=0 ; x<args.length ; x++)

      System.out.println("Argument " + x + " = " + args[x]);
  }
}

Line 3 declares x as an integer variable

Line 4 sets up the loop. It starts at x = 0
and will continue to execute
until we have covered the entire length of the
.argument list.

Line 5 sends the values for
x and argument #x
with the appropriate labels to the
system output device.

 

After compiling this program, run it and enter any number of command line arguments.

If you enter the following command line

java showargs first second 3 four and anything else

the output should be

Argument 0 = first
Argument 1 = second
Argument 2 = 3
Argument 3 = four
Argument 4 = and
Argument 5 = anything
Argument 6 = else

Notice that arguments are separated by a space. The loop can be used to accept any number of arguments. Remember all arguments are strings, including the number 3 in the example above. Be sure to convert any strings to numeric variables before performing any numeric operations.

Go to the next topic: Arrays

Back to the Table of Contents