< Zurück | Inhalt | Weiter >

4.2.1 Command-Line Arguments

When a program is run from the command line, more than just the program name can be supplied. Here are some examples:


$ javac Hi.java

$ mv Acct.java core/Account.java

$ ls -l


In the first example, we invoked a program called javac and gave it the parameter Hi.java, the name of the file containing the Java program that we want javac to compile to Java byte code. (We’ve got a whole chapter on how to set up and run the Java compiler, see Chapter 5.) The mv got two command- line arguments, Acct.java and core/Account.java, which look a lot like pathnames. The ls command has one argument, -l, which in Linux usually indicates, by its leading minus sign, that it is an option for altering the behavior of the command. (In this case it produces the “long” version of the directory listing.)

Even point-and-click GUIs allow such parameters to be supplied, though often not visible to the user. In KDE, one can create a new desktop icon that is a link to an application. Such an icon has a property sheet that lists, on the Execute tab, the command to be run, including any parameters.

In Java, the parameters supplied on the command line are available to the

main() method of a Java class. The signature for this method is:

image

4.2 A Simple Start 101

public static void main(String args[])

From within main(), the various parameters are available as the elements of the array of Strings. The class in Example 4.1 will display those parameters when the program is run.


image

Example 4.1 Java program to dump command-line arguments

/*

* simple command-line parameter displayer

*/


public class CLine

{

public static void main(String [] args)

{

for (int i = 0; i < args.length; i++)

{

System.out.println(args[i]);

}


} // main


} // class CLine


image


We compile and run the example, providing a few command-line parameters:


$ javac CLine.java

$ java CLine hello world file.txt blue hello

world file.txt blue

$


Not all classes will have main() methods, but any can. Even if several classes in a package have main() methods, that is not a problem. Which one will be the “main” main()? It’s the class we specified when we invoked our program. In Example 4.1, the main() that is executed is the one in the CLine


class. Even if CLine used other classes (it does—String is a class) it doesn’t matter if those other classes have main() methods or not.