How to make a method take variable lentgth argument as an input?
Solution:
This example creates sumvarargs() method which takes variable no of int numbers as an argument and returns the sum of these arguments as an output.
public class Main {
static int sumvarargs(int... intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("The sum of the numbers is: " + sum);
}
}
Result:
The above code sample will produce the following result.