[Java Basics] variable parameters, java variable parameters
The following is a simple Applet:
1 import java. util. arrays; 2 3 class lesson6 4 {5 public static void main (String [] args) 6 {7 int array [] = {2, 3, 1, 5, 4, 6}; 8 System. out. println (Arrays. toString (array); 9 System. out. println (getSum (array); 10 // System. out. println (getSum (,); 11} 12 13 static int getSum (int array []) // calculates the sum of elements 14 {15 int sum = 0; 16 for (int I = 0; I <array. length; I ++) 17 sum + = array [I]; 18 return sum; 19} 20}View Code
The Declaration of the getSum (int array []) method limits that it can only accept arrays of the one-dimensional int type. If we try to run Row 10 (the line that is commented out), this will certainly cause an error. This method has obvious disadvantages when you do not know the number of parameters to be input.
Since Java 5Variable parameters.Feature: the number of parameters is variable, and 0 to N parameters can be passed. It must be the last parameter of the method. When a variable parameter method is called, the compiler creates an array for this variable parameter, access variable parameters in the form of an array in the method body.
We will uncomment the above Code and change getSum (int array []) to getSum (int... array) to implement the desired result. The result is as follows:
The following two outputs are available at 21. getSum (int... array) successfully receives two different data numbers.
In addition, the variable parameter must be the last parameter of the method. You can perform a simple test on the above Code.
Variable java Parameters
This is a new feature of JDK or later versions. The for loop is also a newly added function.
The variable parameter is an array, and the number of parameters you pass is put in that array.
This facilitates programmers. If you are not sure about the number of parameters to be passed, we need to write one parameter, two parameters, and three parameters. This is very troublesome. In this method, we only need to write a function and can pass any parameter.
Java variable parameters have length restrictions
The essence of a variable parameter is a parameter array. java requires that the length of an array must be an int integer. That is to say, the maximum length of an array (Variable Parameter) is Integr. MAX_VALUE is probably more than 2.1 billion. This number is basically infinite. No one will pass billions of parameters to a method, right... So rest assured that you are bold enough to pass