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.

How do I convert varargs to an array?

Varargs can be seen as a simplification of array when we need to pass a multiple value as a method parameter. Varargs itself is an array that automatically created, for these reason you will be enabled to do things you can do with array to varargs.

In the example below you can see the messages parameter can be assigned to the String array variables, we can call the length method to the messages parameter as we do with the array. So actually you don’t need to convert varargs to array because varargs is array.

package org.kodejava.lang;

public class VarargsToArray {
    public static void main(String[] args) {
        printMessage("Hello ", "there", ", ", "how ", "are ", "you", "?");
    }

    public static void printMessage(String... messages) {
        String[] copiedMessage = messages;
        for (int i = 0; i < messages.length; i++) {
            System.out.print(copiedMessage[i]);
        }
    }
}

How do I create a method that accept varargs in Java?

Varargs (variable arguments) is a new feature in Java 1.5 which allows us to pass multiple values in a single variable name when calling a method. Of course, it can be done easily using array but the varargs add another power to the language.

The varargs can be created by using three periods (...) after the parameter type. If a method accept others parameter than the varargs, the varargs parameter should be the last parameter to the method. And please be aware that overloading a varargs method can make harder to figure out which method is called in the code.

package org.kodejava.lang;

import java.util.Arrays;

public class VarArgsExample {
    public static void main(String[] args) {
        VarArgsExample e = new VarArgsExample();
        e.printParams(1, 2, 3);
        e.printParams(10, 20, 30, 40, 50);
        e.printParams(100, 200, 300, 400, 500);
    }

    public void printParams(int... numbers) {
        System.out.println(Arrays.toString(numbers));
    }
}

Running the code snippet give you the following output:

[1, 2, 3]
[10, 20, 30, 40, 50]
[100, 200, 300, 400, 500]