Any arguments passed to the program on the command line can be accessed in the main() method of the class specified on the command line:
java Colors red green blue
These arguments are called program arguments. Note that the command name, java, and the class name Colors are not passed to the main() method of the class Colors.
Since the formal parameter of the main() method is an array of String objects, individual String elements in the array can be accessed by using the [] operator.
In Example 3.8, the three arguments "red", "green", and "blue" can be accessed in the main() method of the Colors class as args[0], args[1], and args[2], respectively. The total number of arguments is given by the field length of the String array args. Note that program arguments can only be passed as a list of character strings and must be explicitly converted to other data types by the program, if necessary.
When no arguments are specified on the command line, an array of zero String elements is created and passed to the main() method. This means that the value of the formal parameter in the main() method is never null.
Program arguments supply information to the application, which can be used to tailor the runtime behavior of the application according to user requirements.
public class Colors { public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println("Argument no. " + i + " (" + args[i] + ") has " + args[i].length() + " characters."); } }
Running the program:
>java Colors red green blue Argument no. 0 (red) has 3 characters. Argument no. 1 (green) has 5 characters. Argument no. 2 (blue) has 4 characters.