Java
Java Basics
main
varargs
vargs
Variable Argument
Variable Argument in Java
Varargs - Variable Argument
Varargs is a concept in java which allows passing varying number of arguments to a function. It may be zero or more.
Earlier this was done in two ways,
1. By overloading, having methods with different number of arguments, OR2. Earlier we may put all arguments into an array and pass this array to the function , but now varargs feature automates and hides the process.
When to use varargs :
When we are not sure now many arguments are to be passed to the function, then varargs is a good option.One of the most famous example, which you guys might have used the function :
String.format("This is an integer: %d", intNum);
String.format("This is an integer: %d and a String: %s", intNum, "Hello World");
Example : A sample program to calculate the sum of numbers
public class VargsExample {
public class VargsExample { public static void main(String args[]) { calculate();// no argument calculate(1, 2, 3);// 3 arguments } /** * Function with VARARGS * @param values - will act as an Integer array */ static void calculate(Integer... values) { int total = 0; for (int i : values) { total = total + i; } System.out.println("Total : " + total); } }
Output :
Total : 0 Total : 6
How to pass the varargs to a function :
It is mandatory that, varargs argument(say, Integer... values, in previous example), must be the last argument.i.e,
public void calculateWithCount(Integer... values, int count) { // This declatation is WRONG //It will throw an Exception : Unresolved compilation problem //business logic }
It has to be the otherway,
public void calculateWithCount(int count, Integer... values) { // This declatation is CORRECT //business logic }
Since the varargs is like a array, we can even modify the main(String args[]) with varargs
public static void main(String... args) { //This will work fine }
No comments