Advanced Java: Collections, Generics and More ยท More Language Features

Varargs: Any Number of Arguments

int... lets a method accept zero, one or many arguments, which arrive as an array.

VarargsDemo.java

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);
    }
}

Step by step

  1. Java calls total(), with nums = []. It gets its own variables on the stack. The program starts in main. args holds its command-line arguments (none here).
  2. total() with no arguments: nums is an empty array.
  3. Java moves to the next element of the loop: for (int n : nums).
  4. total() has finished, so its variables are gone.
  5. The value it returned, 0, is stored in none.
  6. Java calls total(), with nums = [4, 6]. It gets its own variables on the stack.
  7. total(4, 6): nums is [4, 6].
  8. n is created on the stack with the value 4.
  9. sum changes from 0 to 4. n goes out of scope and disappears.
  10. n is created on the stack with the value 6.
  11. sum changes from 4 to 10. n goes out of scope and disappears.
  12. Java moves to the next element of the loop: for (int n : nums).
  13. total() has finished, so its variables are gone.
  14. The value it returned, 10, is stored in two.
  15. You can also pass an existing array.
  16. sum is created on the stack with the value 0.
  17. n is created on the stack with the value 1.
  18. sum changes from 0 to 1. n goes out of scope and disappears.
  19. n is created on the stack with the value 2.
  20. sum changes from 1 to 3. n goes out of scope and disappears.
  21. n is created on the stack with the value 3.
  22. sum changes from 3 to 6. n goes out of scope and disappears.
  23. Java moves to the next element of the loop: for (int n : nums).
  24. total() has finished, so its variables are gone.
  25. The value it returned, 6, is stored in arr.
  26. It prints 0 10 6.
  27. 0, 10 and 6: the same method, called with 0, 2 and 3 values.