0Pricing
Java Academy · Lesson

Varargs Parameters

Define methods that accept variable-length argument lists and combine them with arrays.

Varargs Parameters

Varargs (variable-length argument lists) let you define methods that accept any number of arguments of the same type, internally treated as an array.

Declaring Varargs

Use Type... name for a varargs parameter. It must be the last parameter and there can only be one per method.

static int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}

System.out.println(sum());           // 0 (empty array)
System.out.println(sum(1));          // 1
System.out.println(sum(1, 2, 3));    // 6
System.out.println(sum(1, 2, 3, 4)); // 10

// Can also pass an array
int[] arr = {5, 10, 15};
System.out.println(sum(arr));        // 30

All lessons in this course

  1. Method Overloading Rules
  2. Varargs Parameters
  3. Static Fields and Constants
  4. Utility Classes and Static Factory Methods
← Back to Java Academy