Java Variable Arguments
Java variable arguments (varargs) was introduced in java 1.5.usage of varargs is if u want to pass more arguments to the method say example more than 3 or 4 of same data type then we can go for varargs which makes the code simple and neat.
Before varargs developer used two options
- creating a collection like list or set and passing all the data with that
- overloading method with different parameter
lets take method overloading
private int varargsDemo(int i, int j) {
int result =i*j;
return result;
}
private int varargsDemo(int i, int j,int k) {
int result =i*j*k;
return result;
}
Here you can see if you use overloading your code becomes little clumsy and you need to create more number of overloading methods also the main thing is you should know the max number of arguments you want to pass before your write the code.
now consider collections
private int varargsDemo(int [] number) {
int result =i*j*k;
return result;
}
This will be the simple one when compared to overloading but you have to create set ,list or array and need to do all the collection operation like inserting your data into that by yourself .
Why give all these to java and let java take care of it .
Here comes Variable Arguments or Vararags
public class VarargsTest {
public static void main(String args[]){
int result;
VarargsTest var= new VarargsTest();
result =var.varargsDemo(1,3,6,9,7,4);
System.out.println(result);
}
private int varargsDemo(int ...numbers) {
int result = 0;
for(int number:numbers){
result=result*number;
}
return result;
}
}
We need to consider some points before using varargs
- varargs should be given as a last parameter
- varargs may lead to some performance issue since java creates array internally for the variables.
- This can be avoided by using varargs when number of arguments exceeds 3 or 4 else we can use method overloading
Comments
Post a Comment