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.

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

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):

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.

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.

Search for more Java info on this site here:
Custom Search

Please type any questions here.