Using Varargs in Java


Sometimes you might need to write methods that accept an argument that contains multiple values.
In such case an array could be the type to use.


public int calculate(int[] list) {

    int sum = 0;
    for (int i=0; i < list.length; i++) {
        sum += list[i];
    }
    return sum;

}


Instead of using an array, another option could have been to create several overloaded methods that would take different number of arguments.


public int calculate(int a, int b) {
    return a + b;
}

public int calculate(int a, int b, int c) {
    return a + b + c;
}

public int calculate(int a, int b, int c, int d) {
    return a + b + c + d;
}

public int calculate(int a, int b, int c, int d, int e) {
    return a + b + c + d + e;
}


This might be easier but is way less flexible than using an array.
Without making a huge class with thousands of methods,
there is a rather small limit to the number of parameters that this overloaded method will accept.

From Java 5, we can write a method so that it allows a variable number of parameters and let the compiler do the work of packaging the list into an array.
An array is still used internally, but the details are hidden by the compiler.
The code below shows how the calculate method uses variable arguments (varargs):


public int calculate(int...list) {

    int sum = 0;
    for (int item : list) {
        sum += item;
    }
    return sum;

}


The three dots in the method signature tells that you may pass any number of int values to the method.
You may also, as before, pass an array to the method.


calculate(2, 4, 6, 8, 10, 12, 14, 16);
calculate(new int[] {2, 4, 6, 8, 10, 12, 14, 16});


One thing to remember when using varargs is that if it's not the only parameter to a specific method, it has to be placed as the last parameter in the list.
You may not for example use varargs as the first parameter and a string as the second parameter in a method signature.
The string needs to come first in such a case.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: