Here's a simple little program:
Copy Code code as follows:
Import Java.util.Arrays;
Class Lesson6
{
public static void Main (string[] args)
{
int array[]={2,3,1,5,4,6};
System.out.println (arrays.tostring (array));
System.out.println (Getsum (array));
System.out.println (Getsum (2,3,1,5,4,6));
}
static int getsum (int array[])//sum of calculated elements
{
int sum=0;
for (int i=0;i<array.length;i++)
Sum+=array[i];
return sum;
}
}
The declaration of the getsum (int array[]) method qualifies it to accept only arrays of one-dimension int. If we are now trying to run line tenth (the line that is commented on), this will definitely go wrong. This method of declaring the way especially when you do not know to pass the number of parameters, the disadvantage is more obvious.
Starting with JAVA5, a variable parameter appears. Features are: variable number of parameters, you can pass 0 to n; You must be the last parameter of a method; When you call a method of a variable parameter, the compiler implicitly creates an array for the variable parameter, which accesses the variable parameter in the form of an array in the method body.
We cancel the comment on the code above and change getsum (int array[]) to getsum (int ... array) to achieve the results we want. The results obtained are as follows:
From the bottom two output 21 is available, getsum (int ... array) successfully received 2 different numbers of data passed in.
In addition, in practical programming, it is necessary to note that the variable parameter must be the last parameter of the method. You can make a simple change to the code above to experiment.