Variable Arguments in Java

Variable arguments to a function in any language gives us a flexibility while calling the function. The number of arguments to a function are not fixed, and a number of calls can be made to the same function which would otherwise have been impossible without method overloading.

Consider the following example:

You have to write an add function that adds the values of the arguments given to it and returns the sum.

You can possibly achieve this in the following ways:

Method 1:

public int add(int a , int b) {
return a+b;
}
view raw varargs1.java hosted with ❤ by GitHub

Method 2:

public int add(int[] arr) {
sum = 0;
for (int i=0; i<arr.length; i++) {
sum+=arr[i]
}
return sum;
}
view raw varargs2.java hosted with ❤ by GitHub

The first method allows only 2 numbers to be added. If you want to add 3 numbers you cannot use this function. You will have to define another overloaded function.

The second method allows a variable number of numbers to be added. However, whenever you call it, a new int array needs to be defined:

e.g add(new int[]{1,2,3,4,5});

e.g add(new int[]{1,2,3});

and so on.

In comes the variable arguments to save the day.

public int add(int... varargs) {
sum = 0;
for (int i=0; i<arr.length; i++) {
sum+=arr[i];
}
return sum;
}
view raw varargs3.java hosted with ❤ by GitHub

Typical Issues with varargs,

  1. Only one variable argument can be present per method.
  2. Typically, you can mix it with fixed arguments, however, the variable argument has to be at the end in the function parameter list.