Variable Argument (Varargs):
The varrags allows the method
to accept zero or muliple arguments. Before varargs either we use overloaded
method or take an array as the method parameter but it was not considered good
because it leads to the maintenance problem. If we don't know how many argument
we will have to pass in the method, varargs is the better approach.
Advantage of Varargs:
We don't have to provide
overloaded methods so less code.
Syntax of varargs:
The varargs uses ellipsis i.e.
three dots after the data type. Syntax is as follows:
1. return_type method_name(data_type... variableName){}
Simple
Example of Varargs in java:
1.
2. class VarargsExample1{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. }
7.
8. public static void main(String args[]){
9.
10. display();//zero argument
11. display("my","name","is","varargs");//four arguments
12. }
13. }
Test it Now
Output:display method invoked
display method invoked
Another
Program of Varargs in java:
1.
2. class VarargsExample2{
3.
4. static void display(String... values){
5. System.out.println("display method invoked ");
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display();//zero argument
14. display("hello");//one argument
15. display("my","name","is","varargs");//four arguments
16. }
17. }
Test it Now
Output:display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs
Rules for varargs:
While using the varargs, you
must follow some rules otherwise program code won't compile. The rules are as
follows:
- There
can be only one variable argument in the method.
- Variable
argument (varargs) must be the last argument.
Examples of varargs that fails to compile:
1.
2. void method(String... a, int... b){}//Compile time error
3.
4. void method(int... a, String b){}//Compile time error
5.
Example
of Varargs that is the last argument in the method:
1.
2. class VarargsExample3{
3.
4. static void display(int num, String... values){
5. System.out.println("number is "+num);
6. for(String s:values){
7. System.out.println(s);
8. }
9. }
10.
11. public static void main(String args[]){
12.
13. display(500,"hello");//one argument
14. display(1000,"my","name","is","varargs");//four arguments
15. }
16. }
17.
Test it Now
Output:number is 500
hello
number is 1000
my
name
is
varargs
No comments:
Post a Comment