The idea of arrays

If you cast your mind back to the very first example, the method main had the form

public static void main(String argv[]);

The part between the braces that says

String arg[]

Indicates that the method takes a parameter (also known as an argument) of a String array. This means that when the program starts running any thing typed onto the command line after the program name will be contained within this String array. An array is a holder for multiple instances of a data type. So if you run your program with the command

java build one two three

The array arg will contain the string values

"one" "two" and "three"

You can extract any of the values from the array using the square bracket notation. Thus if you wanted to print out the second String value contained within the argv array you could use


System.out.println(argv[1]);

Note that accessing the second value means using 1 and not 2. This is because almost all counting in Java starts from zero and not one. Although you can make an argument that this is perfectly logical, it is something that can constantly catch you out.

The alternative to using an array or some method of holding multiple variables would be to create multiple variables for each value. So for the previous example you might create variables in the form

String sArg1;
String sArg2
String sArg3

Which is much less elegant than having a way of carrying round multiple values within one Array variable.

You can also find out how many elements an array has using it's length method. Thus you could retrieve the number of command line parameters thus

System.out.println(argv[].length);
Last modified: Sunday, 20 September 2015, 07:21 PM