Varargs in Java

Varargs allows a method to accept zero or more arguments of the same type.

Syntax

returnType methodName(type... variableName) {
    // code
}

Example

public class Main {

    static int sum(int... numbers) {
        int total = 0;

        for (int number : numbers) {
            total += number;
        }

        return total;
    }

    public static void main(String[] args) {

        System.out.println(sum(1, 2));
        System.out.println(sum(1, 2, 3, 4));
        System.out.println(sum());
    }
}