Command Line Arguments in Java

By Barry A. Burd

Once upon a time, most Java programmers used a text-based development interface. They typed a command in a plain-looking window, usually with white text on a black background.

text-based interface in java
How dull!

The plain-looking window goes by the various names, depending on the kind of operating system that you use. In Windows, a text window of this kind is a command prompt window. On a Macintosh and in Linux, this window is the terminal. Some versions of Linux and UNIX call this window a shell.

Anyway, back in ancient times, you could write a program that sucked up extra information when you typed the command to launch the program.

MakeRandomNumsFile in java
When you launch MakeRandomNumsFile, you type some extra information.

In the image above, the programmer types java MakeRandomNumsFile to run the MakeRandomNumsFile program. But the programmer follows java MakeRandomNumsFile with two extra pieces of information: MyNumberedFile.txt and 5. When the MakeRandomNumsFile program runs, the program sucks up two extra pieces of information and uses them to do whatever the program has to do. The program sucks up MyNumberedFile.txt 5, but on another occasion the programmer might type SomeStuff 28 or BunchONumbers 2000. The extra information can be different each time you run the program.

The next question is, “How does a Java program know that it’s supposed to snarf up extra information each time it runs?” Since you first started working with Java, you’ve been seeing this String args[] business in the header of every main method. Well, it’s high time you found out what that’s all about. The parameter args[] is an array of String values. These String values are called command line arguments.

Some programmers write

public static void main(String args[])

and other programmers write

public static void main(String[] args)

Either way, args is an array of String values.

Using command line arguments in a Java program

This bit of code shows you how to use command line arguments.

This is how you generate a file of numbers

import java.util.Random;

import java.io.PrintStream;

import java.io.IOException;

 

public class MakeRandomNumsFile {

 

public static void main(String args[]) throws IOException {

 

Random generator = new Random();

 

if (args.length < 2) {

System.out.println("Usage: MakeRandomNumsFile filename number");

System.exit(1);

}

PrintStream printOut = new PrintStream(args[0]);

int numLines = Integer.parseInt(args[1]);

 

for (int count = 1; count <= numLines; count++) {

printOut.println(generator.nextInt(10) + 1);

}

printOut.close();

}

}

If a particular program expects some command line arguments, you can’t start the program running the same way you’d start most of the other normal programs. The way you feed command line arguments to a program depends on the IDE that you’re using — Eclipse, NetBeans, or whatever. Allmycode.com has instructions for feeding arguments to programs using various IDEs.

When the code begins running, the args array gets its values. With the run shown in the image above, the array component args[0] automatically takes on the value "MyNumberedFile.txt", and args[1] automatically becomes "5". So the program’s assignment statements end up having the following meaning:

PrintStream printOut = new PrintStream("MyNumberedFile.txt");

int numLines = Integer.parseInt("5");

The program creates a file named MyNumberedFile.txt and sets numLines to 5. So later in the code, the program randomly generates five values and puts those values into MyNumberedFile.txt. One run of the program gives you this.

running code java

After running the code, where can you find the new file (MyNumberedFile.txt) on your hard drive? The answer depends on a lot of different things. If you use an IDE with programs divided into projects, then the new file is somewhere in the project’s folder. One way or another, you can change Listing 11-7 to specify a full path name — a name like "c:\\Users\\MyName\\Documents\\MyNumberedFile.txt" or "/Users/MyName/Documents/MyNumberedFile.txt".

In Windows, file path names contain backslash characters. And in Java, when you want to indicate a backslash inside a double-quoted String literal, you use a double backslash instead. That’s why “c:\\Users\\MyName\\Documents\\MyNumberedFile.txt” contains pairs of backslashes. In contrast, file paths in the Linux and Macintosh operating systems contain forward slashes. To indicate a forward slash in a Java String, use only one forward slash.

Notice how each command line argument is a String value. When you look at args[1], you don’t see the number 5 — you see the string "5" with a digit character in it. Unfortunately, you can’t use that "5" to do any counting. To get an int value from "5", you have to apply the parseInt method.

The parseInt method lives inside a class named Integer. So, to call parseInt, you preface the name parseInt with the word Integer. The Integer class has all kinds of handy methods for doing things with int values.

In Java, Integer is the name of a class, and int is the name of a primitive (simple) type. The two things are related, but they’re not the same. The Integer class has methods and other tools for dealing with int values.

Checking for the right number of command line arguments

What happens if the user makes a mistake? What if the user forgets to type the number 5 on the first line when you launch MakeRandomNumsFile?

Then the computer assigns "MyNumberedFile.txt" to args[0], but it doesn’t assign anything to args[1]. This is bad. If the computer ever reaches the statement

int numLines = Integer.parseInt(args[1]);

the program crashes with an unfriendly ArrayIndexOutOfBoundsException.

What do you do about this? You check the length of the args array. You compare args.length with 2. If the args array has fewer than two components, you display a message on the screen and exit from the program.

args array in java
The code tells you how to run it.

Despite the checking of args.length, the code still isn’t crash-proof. If the user types five instead of 5, the program takes a nosedive with a NumberFormatException. The second command line argument can’t be a word. The argument has to be a number (and a whole number, at that). You can add statements to to make the code more bulletproof.

When you’re working with command line arguments, you can enter a String value with a blank space in it. Just enclose the value in double quote marks. For instance, you can run the code above with arguments "My Big Fat File.txt" 7.