Indefinite length parameters in java
Indefinite length parameters are parameters with no specified length.
The syntax of the variable-length parameter method is as follows:
返回值 方法名(参数类型...参数名称)
Use the "..." form in the parameter list to define the variable-length parameter. In fact, this variable-length parameter is a For arrays, the compiler will treat the form (int...a) as the form (int[] a).
Example: Write a variable-length parameter method.
/** * 定义不定长参数方法 * * @author pan_junbiao * */ public class MyTest { public static int add(int... a) { int s = 0; for (int i = 0; i < a.length; i++) { s += a[i]; } return s; } public static void main(String[] args) { // 调用不定长参数方法 System.out.println("调用不定长参数方法:" + add(1, 2, 3, 4, 5, 6, 7, 8, 9)); System.out.println("调用不定长参数方法:" + add(1, 2)); } }
Running results:
Recommended learning: Java video tutorial
The above is the detailed content of What are variable length parameters in java?. For more information, please follow other related articles on the PHP Chinese website!