Thursday, 19 November 2009

Command line arguments

It is a way of passing to program some information

through command line

example

class test

{

public static void main ( String args [ ] )
{
       //  for loop to access all command line arguments
for (int i = 0 ; i < args.length ; i ++)
{
System.out.println ("Argument " + (i +1) + " : " + args [i]) ;
} // for loop ends
} // main function ends

} // class ends

Run this class as following

java test one two three

  • Whatever comes after the name of class (seperated by space) , goes into the parameter args which is a String array
  • for loop runs as long as there are elements in the array args which depends on how many we pass

Output:  Argument 1 : one

              Argument 2 : two
              Argument 3 : three

args [ 0 ] holds one
args [ 1 ] holds two
args [ 2 ] holds three