Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Sending Arguments to Applications 41

Sending Arguments to Applications


You can run Java applicationsfrom a command line using java, a program
that invokes the JVM. NetBeans uses this program behind the scenes when
you run programs. When a Java program is run as a command, the JVM
loads the application. The command can include extra items of informa-
tion, as in this example:


java TextDisplayer readme.txt /p


Extra information sent to a program is called an argument. The first argu-
ment, if there is one, is provided one space after the name of the applica-
tion. Each additional argument also is separated by a space. In the preced-
ing example, the arguments are readme.txtand /p.


If you want to include a space inside an argument, you must put quotation
marks around it, 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 Pageand
Titlefrom being treated as separate arguments.


You can send as many arguments as you want to a Java application (within
reason). To do something with them, you must write statements in the
application to handle them.


To see how arguments work in an application, create a new class in the
Java24 project:



  1. Choose File, New File.

  2. In the New File Wizard, choose the category Javaand file type Empty
    Java File.

  3. Give the class the name BlankFillerand click Finish.


Enter the text of Listing 4.2 in the source code editor and save it when
you’re done. Compile the program, correcting any errors that are flagged
by the editor as you type.


LISTING 4.2 The Full Text of BlankFiller.java
1: classBlankFiller {
2: public static voidmain(String[] arguments) {
3: System.out.println(“The “+ arguments[0]
4: + “ “ + arguments[1] + “ fox “

Free download pdf