VarArgs for Integer in Java

An example on using single variable arguments for int in Java.

class VarArgsIntExample
{
public static void main(String args[])
{
sum(1,2,4,5);
sum(1,2);
sum(a);
}


public static void sum(int... a)
{
int sum=0;
for(int i=0;i<a.length;i++)
{
sum+=a[i];
}
System.out.println("The sum is "+sum);
}
}

Output


The sum is 12
The sum is 3

Explanation

The three dots (...) after the data type in the method indicates that variable argument is defined. The type of the var arg is int and the name given to it is a. The var a acts like the reference of an int[]. Proof for this is in the for loop statement a.length where length is a property of the arrays. So by this, a is an array and that's confirmed. 

You'll have to note that the way we call the method sum(int... a) in the main() is not like we're giving an int array to it. It is like passing as many number of arguments which should be summed. You can also pass an array to it instead of those many parameters. But if you declare sum() as sum(int[] a) instead of sum(int... a) that could not be possible. Because, the parameter for the sum(int[] a) is an array and of course, that too a single parameter.

No comments: