Varargs or variable arguments was a feature introduced in Java 5 to reduced code bloat. Java has been criticized as a very noisy language requiring lot of cermonial code to function properly. Varargs is one of the ways to make your methods more flexible and reduce the amount of boilerplate code you have to write.
What is Varargs feature?
Varargs feature allows you to pass variable number of arguments to a method. By using vargs feature you can pass zero to unlimited number of arguments of the same type to a method.
Suppose you want to say hello to all the visitors that come to your house in a single method call. Something along the lines –
1 2 3 4 5 | public void sayHello2 (String guest1, String guest2) { System.out.println ("Hello "+ guest1 + " "+ guest2); |
Since the guests may come in groups of one, two or more you need to devise sayHello, sayHello2, sayHello3 – a clear case of code duplication. One of the guiding priniciples in software engineering is Don’t Repeat Yourself and writing such methods would be a blatant violation of DRY principle.
As an alternative you may pass a Java collection to a method and the method can then operate on individual Java elements. Since we have not yet covered Java Collections, we will not go into the code. But this approach of using Java Collections is so obvious and mandatory that Java provides a shortcut of using it. This shortcut is called varargs. In fact any argument with varargs can be treated as a fixed length array.
Syntax of Varargs
The symbol for varargs in Java is ellipsis i.e … . The three consecutive dots indicate that a variable, indeterminate number of arguments are occuring. The ellipsis is preeceded by the type of the variable as shown below
1 | TypeName.... variableName |
Let’s re-write our method to say hello to any number of guests in a single method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class HelloGuest{ public static void main(String []args){ sayHello("Guest1"); sayHello("Guest903", "Guest783", "Gues566"); // a varargs or variable arguments allows you // to pass even zero arguments // the call below does not print anything // but is a valid call. sayHello(); } /** Now we use varargs to say hello to any number * of guests in one go. **/ public static void sayHello (String... guests) { for(String guest : guests) { System.out.println ("Hello " + guest); } } } |
The output of the above code is –
1 2 3 4 | Hello Guest1 Hello Guest903 Hello Guest783 Hello Gues566 |
As you can see Java interpreted … to be a variable length argument. We used enhanced for loop to iterate over the elements passed to the method and say hello to all guests. Let’s now look at the another, often cited example of varargs.
Another Example of Varargs
We now use variable arguments to write a method that can multiply zero or more numbers to 1 and return the result –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class VariableArgumentsMultiplyDemo{ public static void main(String []args){ int res; res = multiply(1, 1, 2, 3, 5); System.out.println("Multiplying 1,1,2,3,5 gives: " + res); res = multiply(10, 7); System.out.println("Multiplying 10 and 7 gives: " + res); // the next two calls make no sene from the perspective of // multiplication as a mathematical operation. // Nevertheles, they are valid varargs calls res = multiply(1); System.out.println("Multiplying 1 with nothing else: " + res); res = multiply(); System.out.println("Not Multiplying anything gives: " + res); } public static int multiply(Integer... numbers) { int result = 1; for(Integer anInt : numbers) { result *= anInt; } return result; } } |
The output of the code is
1 2 3 4 | Multiplying 1,1,2,3,5 gives: 30 Multiplying 10 and 7 gives: 70 Multiplying 1 with nothing else: 1 Not Multiplying anything gives: 1 |
Note that it is valid to pass zero or one arguments. It may not make much sense to multiply “no numbers” or a number with one, but from Java’s feature perspective it is allowed.
Rules for Varargs
The following rules applyto varargs usage –
- Can be used ONLY in methods or constructors
- Are allowed in constructors
- Cannot be used for variable declaration
- Any method can have maximum ONE varargs argument
- The varargs argument must be the last argument in the method arguments list
Some More Examples of Varargs
Here is a valid example of method using varargs –
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String []args){ add("Fibonacci Series:", 1, 1, 2, 3, 5, 8); } public static void add(String title, Integer... numbers) { String numberSeries = ""; for(int number : numbers) { numberSeries += " "; numberSeries += number; } System.out.print(title + numberSeries); } |
And here are some examples of invalid usage
1 2 3 4 5 | // variable sized argument must be the last argument public void aMethod(Integer... numbers, String title) { } // cannot have more than one variable sized arguments public void aMethod(Integer... numbers, String... title) { } |
That’s all you need to know about varargs for using them effectively.