“varargs” argument in Java Methods
Earlier we discussed on method overloading, it gives same method name and differ by method signature. If we are not sure about number of argument(but same type) for the method, we can’t write one method of each combination of argument list. Code quality recommends maximum 4 overloaded method(with same name) for easy to use and readability. So how to handle that scenario with quality design and better code readability. Let us discuss variable argument(varargs) and extended for loop in Java.
varargs allows the method to accept zero or muliple arguments of same type. Internally, all the arguments are converted to arrays and can be manipulated in the method. Three dots (…) in the method signature to accept variable arguments. The syntax as below,
public static int add( int… numbers ){
// Do method manipulation
}
Enhanced for loop:
Enhanced for loop is more effective to manipulate each element in the array or iterator in collection framework. Syntax of enhanced for loop is ” for (data_type variable: array_name)”. For example,
String languages[] = { “C”, “C++”, “Java”, “Python”, “Ruby”};
for (String sample: languages) {
System.out.println(sample);
}
Combining varargs and enhanced for loop gives most efficient design if we don’t know how many argument we will have to pass in the method. Let us take an example. We have to calculate the average of each batsman score. Here the problem each batsman might have played different number of matches. So we could not write multiple method for each number of matches. “varargs” would be right fit for this design.
package info.javaarch;
public class VarArgsExample{
public static void main(String[] args) {
getBatsManAverage(“Peter”, 51,60,40,20); // Peter played 4 matches
getBatsManAverage(“Scott”, 11,23); // Scott played 2 matches
getBatsManAverage(“Joe”, 4); // Joe played 1 matches
getBatsManAverage(“Dave”, 37,11,40,20,14,65,32,84,49,91); // Dave played 10 matches
getBatsManAverage(“John”, 84,32,74,12,43,21,65,32,15,90,47); // John played 11 matches
getBatsManAverage(“Zahir”); // Zahir played no matches.
}
// scores is varargs argument and enhanced for loop to iterate the elements.
public static void getBatsManAverage(String name, Integer… scores ){
if(scores.length != 0) {
int count =0, totalScore = 0;
for(Integer score : scores) {
totalScore = totalScore + score;
count++;
}
System.out.println(“Average score of batsman ” + name + ” is:” + totalScore / count+”.”);
}else {
System.out.println(“Average score of batsman ” + name + ” is 0.”);
}
}
}
Rules for varargs:
- There can be only one variable argument in the method.
- Variable argument (varargs) must be the last argument.
- varargs would be considered only if no match the method by overloading or by widening or by auto-boxing of arguments. Do not confuse now. Start using varargs in your code. you would learn all the restriction while writing the method.
Be effective and start use varargs at right place!!!