Original Source : www.beginwithjava.com
Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values. We write the method as shown here:
public static int sum(int ... list) { //write code here }
int... list
This statement declares list to be a variable length formal parameter. In fact, list is an array wherein each element is of type int, and the number of elements in list depends on the number of arguments passed.
/** * This Program demonstrates * variable length arguments. */ public class VarArgs { public static void main(String[] args) { System.out.println("The sum of 5 and 10 is " + sum(5, 10)); System.out.println("The sum of 23, 78, and 56 is " + sum(23, 78, 56)); System.out.println("The sum when no parameter is passed is " + sum()); int[] numbers = { 23, 45, 89, 34, 92, 36, 90 }; System.out.println("The sum of array is " + sum(numbers)); } /** * The sum method takes * variable number of arguments. */ public static int sum(int... list) { int total = 0; // add all the values in list array for (int i = 0; i < list.length; i++) { total += list[i]; } return total; } }
Output :
The sum of 5 and 10 is 15
The sum of 23, 78, and 56 is 157
The sum when no parameter is passed is 0
The sum of array is 409
Original Source : www.beginwithjava.com