Java Command-Line Arguments

There may be the situation where you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program’s name on the command line when it is executed. They are stored as strings in a String array passed to the args parameter of main( ). So, accessing the command-line arguments inside a Java program is quite easy.

The first command-line argument is stored at args[0], the second at args[1], and so on. For example, the following program displays all of the command-line arguments that it is called with:

 * Display all command-line arguments.
class CommandLine {
    public static void main(String args[]) {
        for (int i = 0; i < args.length; i++)
            System.out.println("args[" + i + "]: " + args[i]);

Try executing this program, as shown here:

java CommandLine this is a test 100 -1

When you do, you will see the following output:

args[0]: this 
args[1]: is 
args[2]: a 
args[3]: test 
args[4]: 100 
args[5]: -1


Varargs: Variable-Length Arguments

Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called varargs and it is short for variable-length arguments.

  • A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method.
  • A variable-length argument is specified by three periods (…).
  • For example, here is how vaTest( ) is written using a vararg:
static void vaTest(int ... v) {

This syntax tells the compiler that vaTest( ) can be called with zero or more arguments. As a result, v is implicitly declared as an array of type int[ ]. Thus, inside vaTest( ), v is accessed using the normal array syntax. Here is the preceding program rewritten using a vararg:

 * Demonstrate variable-length arguments.
class VarArgs { // vaTest() now uses a vararg.
    static void vaTest(int... v) {
        System.out.print("Number of args: " + v.length + " Contents: ");
        for (int x : v)
            System.out.print(x + " ");

    public static void main(String args[]) {
    // Notice how vaTest() can be called with a
    // variable number of arguments.
        vaTest(); // no args
        vaTest(10); // 1 arg
        vaTest(1, 2, 3); // 3 args

The output of the program is:

Number of args: 0 Contents: 
Number of args: 1 Contents: 10 
Number of args: 3 Contents: 1 2 3 

The output shows that method vaTest() takes variable number of arguments and hence it is varargs method.