Variable
Argument, termed as varargs are introduced in JDK 1.5 which allows us
to write methods which can accept any (zero or multiple) number of
arguments. By default, vararg argument is an array. The syntax of vararg
method is as follows:
return_data_type method_name(argument_data_type... argument_name){}
void sum(int... values){}
Note: If you want to use any other arguments along with vararg then vararg must be the last argument in the method as shown below:
void sum(int value1, int... values){}
void sum(int... values, int value1){}
class A{
public static void main(String args[]){
A obj = new A();
obj.sum(); // 0 arguments
obj.sum(3); // 1 argument
obj.sum(3, 5); // 2 arguments
obj.sum(3, 5, 7); // 3 arguments
}
void sum(int... values){
int sum = 0;
for(int value:values){
sum += value;
}
System.out.println("SUM:"+sum);
}
}
If we compile and run the preceding program you will get the following output: SUM:0
SUM:3
SUM:8
SUM:15
Thus, a method with vararg argument can accept any number of arguments.