Using Command-Line Arguments

Suppose you wish to use the Notepad application in Microsoft Windows. You can, of course, simply type "notepad" in a console window, and the application will launch.

Now suppose that you had already created a text file "C:\myfile.txt" and wanted to print that file to the default printer using Notepad. Rather than launching Notepad and then opening the file from within the program using the menus, and then using the menus again to print the file -- we could do all of this in one step using "command line arguments":

In this case, we could type

notepad /P c:\test.txt

The "/P" and "c:\test.txt" in the command line instruction given above are called command line arguments. "/P" tells the program to print something, while "c:\test.txt" tells the program the name and location of the file with which we want to do something. (Certain command line arguments, like the "/P" above may also be called "switches" or "flags" in some cases)

When we use the java virtual machine to run a java program, we can also specify additional command line arguments that the program can then use to modify how it behaves.

If we had wanted to use a java text-editor we made called MyJavaNotepad instead of Microsoft's notepad application, we might type something similar to the following:

java MyJavaNotepad /P c:\test.txt

As a more general example, to pass the three arguments to a java program named "MyProgram", we use the following syntax:

java myProgram firstArgument secondArgument thirdArgument

Of course, 3 is not a magic number here. We can have any number of arguments for a given program -- the program must just know what to do with them.

Inside our java source code, we can access the command line arguments through the String array called "args". We see this in the main method signature:

public static void main(String[] args)

We will talk more about arrays later, but for now -- suffice it to say that "args[0]" stores as a String the first argument passed to the program. "args[1]" stores as a String the second argument. "args[2]" stores the third, and so on...

As an example, consider the class Switcherro shown below:

public class Switcheroo{
  public static void main(String[] args) {
    String s1 = args[0];
    String s2 = args[1];
    System.out.println(s2);
    System.out.println(s1);
  }
}

Here's what happens when we provide arguments of "bob" and "fred" to Switcheroo:

$ java Switcheroo bob fred
fred bob