Command line arguments

Main method in java has String array as an argument. Why main method is having a argument? Answer of this question is allowing user to provide input at execution time. All information provided by user stored in argument of main method. These arugment helps in creating a command. For example we want to write a command which will copy one file to another file. We will write a program and file names will be taken at execution time in form of command line arguments.


class command
public static void main(String arg[])
int i;

/* compiled by : javac
executed by : java command ram hanuman

Above example demonstrating use of command line arguments. All arguments specified on command prompt stored in string array arg. first argument is stored in array at index 0, second argument is stored in array at index 1. In case if more arguments are specified at command line those arguments are also stored in array.

    for( i=0 ; i < arg.length ; i++ )

Condition specified in for loop has "arg.length". Every array has a property "length" in java. Array name can be used with dot operator to access length.

"arg.length" returns 2, because number of arguments specified on command line are 2.