Previous Section  < Day Day Up >  Next Section

Sending Arguments to Applications

Because Java applications are run from a command line, you can send information to applications at the same time you run them. The following hypothetical example uses the java interpreter to run an application called Textdisplayer, and it sends two extra items of information to the application, readme.txt and /p:


java TextDisplayer readme.txt /p


Extra information you can send to a program is called an argument. The first argument, if there is one, is provided one space after the name of the application. Each additional argument is also separated by a space.

If you want to include a space inside an argument, you must put quotation marks around the argument, as in the following:


java TextDisplayer readme.txt /p "Page Title"


This example runs the Textdisplayer program with three arguments: readme.txt, /p, and Page Title. The quote marks prevent Page and Title from being treated as separate arguments.

You can send as many arguments as you want to a Java application. In order to do something with them, however, you have to write some statements in the application to handle them.

To see how arguments work in an application, create a new file in your word processor called Blanks.java. Enter the text of Listing 4.2 into the file and save it when you're done. Compile the program, correcting any errors that are caused by typos.

Listing 4.2. The Full Text of Blanks.java

1: class Blanks {

2:     public static void main(String[] arguments) {

3:         System.out.println("The " + arguments[0]

4:             + " " + arguments[1] + " fox "

5:             + "jumped over the "

6:             + arguments[2] + " dog.");

7:     }

8: }


To try out the Blanks application, run it with a Java interpreter such as the JDK's java tool. Give it three adjectives of your own choosing as arguments, as in the following example:


java Blanks retromingent purple lactose-intolerant


The application uses the adjectives to fill out a sentence. Here's the one produced by the preceding three arguments:


The retromingent purple fox jumped over the lactose-intolerant dog.


Try it with some of your own adjectives, making sure to always include at least three of them.

Arguments are a useful way to customize the performance of a program. They often are used to configure a program so it runs a specific way. Java stores arguments in arrays, groups of related variables that all hold the same information. You'll learn about arrays during Hour 9, "Storing Information with Arrays."

Watch Out!

When you run the Blanks application, you must include at least three words as command-line arguments. If not, you'll see an intimidating error message mentioning an ArrayOutOfBoundsException, something that will be complete gobbledygook for another five hours.


    Previous Section  < Day Day Up >  Next Section