Sending Arguments to apps

Because Java apps are run from a command line, you can send information to apps at the same time you run them. The following hypothetical example uses the java interpreter to run an app called Textdisplayer, and it sends two extra items of information to the app, 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 app. 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 app. In order to do something with them, however, you have to write some statements in the app to handle them. To see how arguments work in an app, create a new file in your word processor called 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
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 app, 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 app 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 app, 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.