2/16/11

Varargs implementation example


public class VarArgsExample {


    //simple method to illustrate the use of varargs
    void display(int... a) {
        System.out.println("display method :  length -->" + a.length);
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        System.out.println("display method :  sum of the arguments -- >" + sum);
    }


    //using arrays as varargs
    void sumArrays(int[]... intArrays) {
        int sum, i, j;


        sum = 0;
        for (i = 0; i < intArrays.length; i++) {
            for (j = 0; j < intArrays[i].length; j++) {
                sum += intArrays[i][j];
            }
        }
        System.out.println("sumArrays method : The sum of the numbers is: " + sum);


    }


    public static void main(String args[]) {
        VarArgsExample va = new VarArgsExample();
        va.display(1, 2, 3);
        va.sumArrays(new int[]{1, 2, 3}, new int[]{4, 5, 6}, new int[]{100, 200});
    }
}

No comments:

Post a Comment

Popular Posts