Variable number of arguments in Java

Before Java 5.0, all methods could have fixed number of arguments.

In Java 5.0, Sun introduced variable number of arguments concept. With variable number of arguments, you can pass any number of arguments to same method. You do not need to create a separate method.

Below example explains how to use variable number of arguments in Java. Note that we have used data type as int…

… indicate that there will be variable number of arguments. Arguments are passed as an array and can be retrieved using array syntax.

package other;

/**
 * Created by Sagar on 20-04-2016.
 */
public class VarArgs {

    public static void main(String [] args){
        add(2,3);
        add(4,5,6);
        add(7,8,9,10,11,12);
    }

    public static void add(int... arg){
        System.out.println("Total number of arguments -> " + arg.length);
        int sum = 0;
        for(int a : arg){
            sum += a;
        }

        System.out.println("Sum of numbers is -> " + sum);
    }
}

Here is the output of above Java Example.

Total number of arguments -> 2
Sum of numbers is -> 5
Total number of arguments -> 3
Sum of numbers is -> 15
Total number of arguments -> 6
Sum of numbers is -> 57

You may also like...