Java Method Command-Line Arguments

Introduction

We can pass data into a program via command-line arguments to main().

Java stores the command-line arguments inside a String array via the args parameter of main().

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:

// Display all command line arguments.
public class Main {
  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 

The following output:

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

All command-line arguments are passed as strings.




PreviousNext

Related