Java - Example of Variable Length Argument List.
Java Variable Length Argument List - in this technique we can define a method having variable length argument list of variables.
In this code snippet we will declare a method with variable length argument list, method name will be sum and we will pass 2, 3, 4, 5 and 6 arguments.
Java Code Snippet - Example of Variable Length Argument List
//Java - Example of Variable Length Argument List.
class VariableLengthArgList
{
public static int sumOfNumbers(int... num){
int sum=0;
for(int n:num){
sum+=n;
}
return sum;
}
public static void main(String args[])
{
System.out.println("SUM 1: "+ sumOfNumbers(10,20));
System.out.println("SUM 2: "+ sumOfNumbers(10,20,30));
System.out.println("SUM 3: "+ sumOfNumbers(10,20,30,40));
System.out.println("SUM 4: "+ sumOfNumbers(10,20,30,40,50));
System.out.println("SUM 5: "+ sumOfNumbers(10,20,30,40,50,60));
}
}
SUM 1: 30
SUM 2: 60
SUM 3: 100
SUM 4: 150
SUM 5: 210