How do I pass a variable number of arguments to a method in Java?

You can use varargs to let a method accept any number of arguments of the same type. Declare a varargs parameter by adding three dots (...) after its type.

In this example, you will create a method that adds integers. You can call it with two numbers, several numbers, or no numbers.

Source code

public class VarargsExample {
    void main() {
        IO.println("Sum of two numbers: " + sum(10, 20));
        IO.println("Sum of four numbers: " + sum(5, 10, 15, 20));
        IO.println("Sum with no arguments: " + sum());

        int[] numbers = {3, 6, 9};
        IO.println("Sum of array elements: " + sum(numbers));
    }

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

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

        return total;
    }
}

Explanation

The sum() method declares a varargs parameter:

int sum(int... numbers) {

The declaration int... numbers lets callers pass zero or more int values. Inside the method, numbers is an int[] array.

For example, this call passes two values:

sum(10, 20)

Inside the method, numbers contains 10 and 20.

The method starts with a total of zero, then adds each element:

int total = 0;

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

The statement total += number adds the current number to total. After the loop finishes, the method returns the total.

When you call the method without arguments:

sum()

Java supplies an empty array. The loop has no elements to process, so the method returns 0.

You can also pass an existing array directly:

int[] numbers = {3, 6, 9};
sum(numbers);

The method reads the array elements and returns 18.

Run the example

Compile and run the file:

javac VarargsExample.java
java VarargsExample

Output

Sum of two numbers: 30
Sum of four numbers: 50
Sum with no arguments: 0
Sum of array elements: 18

Rules to remember

A method can have only one varargs parameter, and it must be the last parameter.

For example, this declaration is valid:

int sum(String label, int... numbers)

This declaration is invalid because another parameter appears after the varargs parameter:

int sum(int... numbers, String label)

Use varargs when callers should be able to supply different numbers of values without creating an array explicitly.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.