Java Examples - Using Varargs Variable Arguments

Java 实例Java Examples

Java 1.5 provides a new feature called varargs, which are variable-length arguments.

"Varargs" means "variable number of arguments". Sometimes it is simply called "variable arguments".

To define a method with a variable number of arguments: simply add three consecutive dots (i.e., "...", the ellipsis in English) between the "type" and "parameter name" of a formal parameter, and it can match an indefinite number of actual arguments.

The following example creates the sumvarargs() method to calculate the sum of all numbers:

Main.java file

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); } }

The output of the above code is:

数字相加之和为: 55

Java 实例Java Examples

Other Extensions