Arguments


Command-Line Arguments
Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program’s name on the command line when it is executed. The command-line arguments inside a Java program are stored as strings in the
String array passed to main().

AddEvenValues.java (adding up command-line arguments)
public class AddEvenValues {
  public static void main( String args[ ] ) { 
    int  sum = 0;
    // Add up the even values.
    for ( int i = 0; i < args.length; i++ )
      if ( Integer.parseInt( args[i] ) % 2 == 0 ) 
        sum += Integer.parseInt( args[i] );
    System.out.print( sum );
  }
}
shell> java AddEvenValues  

Output:           Result:

Variable Number of Arguments
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows:
    typeName... parameterName
In the method declaration, specify the type followed by an ellipsis (
...). Only one variable-length parameter may be specified in a method. This parameter must be the last parameter, and any regular parameters must precede it.

FindMax.java (finding the max from the command-line arguments)
public class FindMax {
  public static void main( String args[ ] ) {
    switch ( args.length ) {
      case 0:
        System.out.print( false );
        break;
      case 1:
        System.out.print( Integer.parseInt(args[0]) );
        break;
      case 2:
        printMax( Integer.parseInt(args[0]), Integer.parseInt(args[1]) );
        break;
      case 3:
        printMax( Integer.parseInt(args[0]), Integer.parseInt(args[1]),
                  Integer.parseInt(args[2]) );
        break;
      case 4:
        printMax( Integer.parseInt(args[0]), Integer.parseInt(args[1]),
                  Integer.parseInt(args[2]), Integer.parseInt(args[3]) );
        break;
      default:
        System.out.print( false );
        break;
    }
  }
  public static void printMax( int... numbers ) {
    int result = numbers[0];
    for ( int i = 1; i < numbers.length; i++ )
      if ( numbers[i] > result )  result = numbers[i];
    System.out.print( result );
  }
}
shell> java FindMax  

Output:           Result:




      “We must be willing to let go of the life we planned    
      so as to have the life that is waiting for us.”
      ― Joseph Campbell