|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
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! | |
Search for code examples on this site
