Passing Variable Arguments to a function in Java using varargs – Tutorial & Example

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

calculateSum(1,2);

Calling function with 4 arguments i.e. four ints

calculateSum(1,2,3,4);

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.

int calculateSum(int... nums);

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.

/*
 * Accepts variable number of arguments and 
 * calculate sum of all the elements passed.
 */
int calculateSum(int... nums)
{
	int sum = 0;
	for(int num : nums)
	{
		sum = sum + num;
	}
	return sum;
}

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.

int sum = ex.calculateSum(1,2,3);

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

int []arr ={1,3,5,7,9};
int sum = ex.calculateSum(arr);

Let’s complete example as follows,

package com.thispointer.varargs.example1;

public class Example {

	/*
	 * Accepts variable number of arguments and calculate sum of all the
	 * elements passed.
	 */
	int calculateSum(int... nums) {
		int sum = 0;
		for (int num : nums) {
			sum = sum + num;
		}
		return sum;
	}

	public static void main(String[] args) {

		Example ex = new Example();

		int sum = ex.calculateSum(1, 2);
		System.out.println(sum);

		sum = ex.calculateSum(2, 4, 5, 7);
		System.out.println(sum);

		int[] arr = { 1, 3, 5, 7, 9 };
		sum = ex.calculateSum(arr);
		System.out.println(sum);

	}

}

Ouput:

3
18
25

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

1 thought on “Passing Variable Arguments to a function in Java using varargs – Tutorial & Example”

  1. Pingback: How to pass an ArrayList to varargs method – thisPointer.com

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top