Do you know that we can pass a variable length argument lists in the method.This can be done by passing the datatype followed by an ellipsis(...) and then variable name.The ellipsis indicates that method can receive variable length of arguments of specific type.We can also use method overloading on this method.The ellipsis passed in the method is taken as the array of specific type.So we can apply the array operations on this variable length parameter list.
In the above example i have created a method which takes a variable number of arguments.Then i have applied a for loop to get the sum of elements.In main method i have supplied 2 arguments then 3 arguments and then 4 arguments to get the sum of those numbers.
So tgis is a great thing we can apply in our programs where we don't know how much arguments have to be passed in the method which makes our problem simple.
For Example:
package examples;
public class VarArguments {
public static int sum(int ... numbers){
int res=0;
for(int number:numbers){
res=res+number;
}
return res;
}
public static void main(String[] args) {
int a=12;
int b=13;
int c=14;
int d=15;
System.out.println("a="+a+"\nb="+b+"\nc="+c+"\nd="+d);
System.out.println("Sum of a and b is "+sum(a,b));
System.out.println("Sum of a,b and c is "+sum(a,b,c));
System.out.println("Sum of a,b,c and d is "+sum(a,b,c,d));
}
}
Output:
a=12
b=13
c=14
d=15
Sum of a and b is 25
Sum of a,b and c is 39
Sum of a,b,c and d is 54
package examples;
public class VarArguments {
public static int sum(int ... numbers){
int res=0;
for(int number:numbers){
res=res+number;
}
return res;
}
public static void main(String[] args) {
int a=12;
int b=13;
int c=14;
int d=15;
System.out.println("a="+a+"\nb="+b+"\nc="+c+"\nd="+d);
System.out.println("Sum of a and b is "+sum(a,b));
System.out.println("Sum of a,b and c is "+sum(a,b,c));
System.out.println("Sum of a,b,c and d is "+sum(a,b,c,d));
}
}
Output:
a=12
b=13
c=14
d=15
Sum of a and b is 25
Sum of a,b and c is 39
Sum of a,b,c and d is 54
In the above example i have created a method which takes a variable number of arguments.Then i have applied a for loop to get the sum of elements.In main method i have supplied 2 arguments then 3 arguments and then 4 arguments to get the sum of those numbers.
So tgis is a great thing we can apply in our programs where we don't know how much arguments have to be passed in the method which makes our problem simple.
0 comments:
Post a Comment