Home >Java >javaTutorial >Detailed explanation of the example code of variable parameters in java
This article mainly introduces java Variable parametersDetailed explanation and related information of examples. Friends in need can refer to the following
java Detailed explanation of variable parameters
Variable parameters (Varargs) allow programmers to declare a method that accepts a variable number of parameters.
Variable parameters are also a new feature that appeared in JDK5.0.
Variable parameters are essentially an array. For a method that declares variable parameters, we can pass either discrete values or array objects.
But if the parameters in the method are defined as arrays, then only array objects can be passed instead of discrete values.
Note that variable parameters must be the last parameter in the method declaration. A method cannot have two or more variadic parameters.
Attached is an example program:
public class TestVarargs { private static int sum(int... nums)// 可变参数本质上是数组,但是如果在函数中声明为数组形式,就只能以数组形式调用,而不能用离散的值 { int sum = 0; for (int num : nums) { sum += num; } return sum; } public static void main(String[] args) { int result = sum(1, 3); System.out.println(result); result = sum(1, 2, 3, 4); System.out.println(result); // 可以用数组形式调用 result = sum(new int[] { 3, 4, 5 }); System.out.println(result); } }
The above is the detailed content of Detailed explanation of the example code of variable parameters in java. For more information, please follow other related articles on the PHP Chinese website!