Advanced Java: Collections, Generics and More ยท More Language Features
int... lets a method accept zero, one or many arguments, which arrive as an array.
public class VarargsDemo {
static int total(int... nums) { // any number of ints, received as an array
int sum = 0;
for (int n : nums) {
sum += n;
}
return sum;
}
public static void main(String[] args) {
int none = total();
int two = total(4, 6);
int arr = total(new int[]{1, 2, 3});
System.out.println(none + " " + two + " " + arr);
}
}total(), with nums = []. It gets its own variables on the stack. The program starts in main. args holds its command-line arguments (none here).for (int n : nums).total() has finished, so its variables are gone.none.total(), with nums = [4, 6]. It gets its own variables on the stack.n is created on the stack with the value 4.sum changes from 0 to 4. n goes out of scope and disappears.n is created on the stack with the value 6.sum changes from 4 to 10. n goes out of scope and disappears.for (int n : nums).total() has finished, so its variables are gone.two.sum is created on the stack with the value 0.n is created on the stack with the value 1.sum changes from 0 to 1. n goes out of scope and disappears.n is created on the stack with the value 2.sum changes from 1 to 3. n goes out of scope and disappears.n is created on the stack with the value 3.sum changes from 3 to 6. n goes out of scope and disappears.for (int n : nums).total() has finished, so its variables are gone.arr.0 10 6.