In this article we will discuss how to pass variable number of arguments of a type in a function in java using varargs.

Passing Variable Arguments to a function

Let’s write a function that accepts variable number of same type for example int in this case i.e.

Calling function with 2 arguments i.e. two ints

Calling function with 4 arguments i.e. four ints

To create this type of function we will use varargs provided by java. For declaring it, use elipsis (…) along with type to indicate that this function can accept variable number of arguments of a given type i.e.

This function can accept variable number of integer arguments and will internally convert them to an int array and assign it to reference name nums.

Let’s see its implementation i.e.

Here, vararg nums will be handled as an array inside the function body. All the elements passed in it will be present inside this array. It just iterated over the array and calculated the sum of all elements in the array and returned the value.

We can call this type of function by passing each argument seperated by comma i.e.

Or we can also pass an array to the function which is expecting variable arguments i.e.

Let’s complete example as follows,


Rules for declaring Functions with vargs

There are certain rules that we need to follow while declaring a function that accepst variable arguments using vargs i.e.

  • vararg (Variable argument) should be the last in the argument list.
  • Maximum one vararg ( variable argument) can be in the argument list.

Passing an ArrayList to vararg method parameter