VarArgs.java

Download VarArgs.java

 1: // Short demo of using VarArgs.  Here a method "sum" can take
 2: // any number of int arguments, or an array of ints.
 3: //
 4: // Written 1/2010 by Wayne Pollock, Tampa Florida USA
 5: 
 6: public class VarArgs
 7: {
 8:    public static void main ( String... args )
 9:    {
10:       System.out.println( "sum(): " + sum() );
11:       System.out.println( "sum(1): " + sum(1) );
12:       System.out.println( "sum(1,2): " + sum(1, 2) );
13:       int[]nums = new int[]{4,5,6};
14:       System.out.println( "sum(int[]{4,5,6}): " + sum(nums) );
15:    }
16: 
17:    static int sum ( int... args )
18:    {
19:       int total = 0;
20:       for ( int num : args )
21:           total += num;
22:       return total;
23:    }
24: }