Command-Line Arguments
Recall that the declaration of the main method must look like:
public static void main(String[] args)The String[] args portion of the declaration is a String array of command-line
arguments – values that can be supplied to the program when it is executed. You can then use
these arguments as you would any other String array.
Providing command-line arguments
This section will describe how to use command-line arguments when you run your program from the terminal.
Suppose the class with the main method is called Test. Then you would run your program
from the terminal by typing:
java TestTo supply command-line arguments, simply type input values after java Test when you
execute your program. Separate each argument with a space. Each argument will be placed in
the String[] args array. Suppose you want to get a person’s name, age, and GPA as
command-line arguments. Then you might type:
java Test Bob 20 3.45The values “Bob”, “20”, and “3.45” will be placed in the args array. “Bob” will be at index
0, “20” will be at index 1, and “3.45” will be at index 2.
Using command-line arguments
We can access command-line arguments within the main method by saying args[i], where i
is the index of the argument. For example, to store the name, age, and GPA from above:
public static void main(String[] args)
{
String name = args[0]; //name = "Bob"
int age = Integer.parseInt(args[1]); //age = 20
double gpa = Double.parseDouble(args[2]); //gpa = 3.45
}Of course, this program will crash if the user mistakenly doesn’t enter any command-line
arguments. To tell if they did, we can make sure args.length (the length of the command-line
argument array) is what we expect. If not, we can print an error and exit. Here’s how:
public static void main(String[] args)
{
if (args.length != 3)
{
//print a descriptive error message
System.out.println("Usage: java Test name age gpa");
//This command immediately exits the program
System.exit(0);
}
//We know we have 3 command-line arguments
String name = args[0];
int age = Integer.parseInt(args[1]);
double gpa = Double.parseDouble(args[2]);
}