Here is a simple little program:
Copy the 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[])//Calculate the sum of 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 limits it to only accept one-dimensional arrays of type int. If we now try to run line 10 (the commented line), we will definitely get an error. This method of declaration has obvious disadvantages, especially when the number of parameters to be passed is not known.
Starting from Java5, variable parameters appeared. The characteristics are: the number of parameters is variable, and 0 to N can be passed; it must be the last parameter of the method; when calling a method with variable parameters, the compiler implicitly creates an array for the variable parameters, and an array is included in the method body to access variable parameters.
We uncomment the above code and change getSum(int array[]) to getSum(int ... array) to achieve the results we want. The results obtained are as follows:
From the two outputs of 21 below, we can see that getSum(int ... array) successfully accepted the input of two different data numbers.
Another point that needs special attention in actual programming is that the variable parameter must be the last parameter of the method. You can make simple changes to the above code for testing.