Java var-args(variable-argument) was the concept first introduced in JDK1.5. As the name suggests, it helps us to create a method which can accept a variable number of arguments based on our varying needs.
Prior to JDK1.5, if we wish to create a method which can accept any number of arguments, we would probably opt :
Var-args functionality in Java helps us achieve this objective more elegantly.
Var-args or variable arity in Java is represented by three dots known as an ellipsis( … ):
public static int sum(int... nums){ int sum = 0; for(int num : nums){ sum = sum + num; } return sum; }
The sum() method accepts a var-args parameter ‘nums‘ and returns the sum of all these numbers as an output. The sum() method can be invoked from the main() method in any of the following ways:
sum(); // returns 0 sum(10); // returns 10 sum(10,20); // returns 30 sum(10,20,30,40); // returns 100 sum(new int[]{10, 20, 30}); //returns 60
Clearly, it is valid to pass an array to the var-args argument. Rather, var-args internally creates an implicit array to store all the values and pass it to the method argument.
There are few important points we need to consider when working with var-args in Java:
public static int sum(int... nums) //valid public static int sum(int ...nums) //valid public static int sum(int...nums) //valid public static int sum(int nums...) //compile-time error public static int sum(...int nums) //compile-time error
public int sum(int... scores, String... names) //compile-time error
void sendMsg(String... names, String msg, int count) // compile-time error void sendMsg(String msg, int count, String... names) //valid void sendMsg(int count, String msg, String... names) //valid
public static int sum(int... nums) public static int sum(int[] nums) // compile-time error - invalid overload
In this tutorial, we covered variable arity in Java and how we can leverage it to avoid redundant code and promote reusability. We also now know the basic rules which we need to follow when dealing with Java code making use of var-args.