Variable length Argument Lists

7.9 Variable length Argument Lists

Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values. We write the method as shown here:
public static int sum(int ... list)
{
    //write code here
}       
int ... list
This statement declares list to be a variable length formal parameter. In fact, list is an array wherein each element is of type int, and the number of elements in list depends on the number of arguments passed.
/**
 * This Program demonstrates
 * variable length arguments.
 */
public class VarArgs
{
   public static void main(String[] args)
   {
      System.out.println("The sum of 5 and 10 is " + sum(5, 10));
      System.out.println("The sum of 23, 78, and 56 is "
                         + sum(23, 78, 56));
      System.out.println("The sum when no parameter is passed is "
                         + sum());

      int[] numbers = { 23, 45, 89, 34, 92, 36, 90 };

      System.out.println("The sum of array is " + sum(numbers));
   }

   /**
    * The sum method takes
    * variable number of arguments.
    */
   public static int sum(int... list)
   {
      int total = 0;

      // add all the values in list array
      for (int i = 0; i < list.length; i++)
      {
         total += list[i];
      }

      return total;
   }
} 
Output :
The sum of 5 and 10 is 15
The sum of 23, 78, and 56 is 157
The sum when no parameter is passed is 0
The sum of array is 409

Using Command-Line Arguments

Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). In java, main method looks like this:
public static void main(String[] args) 
This parameter args is an array name. As its declaration indicates, it is used to reference an array of Strings. The array that is passed into the args parameter comes from the command line. The first command-line argument is stored at args[0], the second at args[1], and so on. For example, the following program displays all of the command-line arguments that it is called with:

/**
 * This program displays    
 * all command-line arguments.
 */

public class CommandLine
{
    public static void main(String[] args)
    {
        for(int i=0; i<args.length; i++)
            System.out.println("args[" + i + "]: " + args[i]);
    }
}

No comments:

Post a Comment

Pages