Variable arguments(Varargs)
Varargs is Variable arguments, this feature has been added in Java 5. This is the feature that enables methods to receive variable numbers of arguments
Syntax for Varargs:
public void displayVar(int count, String… args) { }
The Varargs includes three dots … which is called ellipses.
The three periods after the parameter’s type indicate that the argument may be passed as an array .
Conditions for using Varargs:
- Varargs should come last in the parameter list.
int sum(int…a,floatc) // will result in compile time error as Varargs should be last argument.
- Datatype of Varargs should be same.
- Only one set of Varargs is allowed .
int sum(int…a,int…b) // compile time error, as there is only one Variable argument is allowed.
Example for Varargs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.j2eereference.varArgs; public class VarargsExample { public static void Vardisplay(int id, String... Varargs) { System.out.println("Author Id is "+id); for(String arg: Varargs) { System.out.println(arg); } System.out.println("******************"); } public static void main(String args[]) { Vardisplay(1, "Name 1 ", "25"); Vardisplay(2, "Name 2 ", "26", "India"); } } |
Output
Author Id is 1
Name 1
25
******************
Author Id is 2
Name 2
26
India
******************
Varargs Overloading :
We Can do Overloading in Varargs.
Consider the example in this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.j2eereference.varArgs; public class Overloading { static void vardisplay(int...vargs) { System.out.println("Inside method with int Varargs"); System.out.println("Length of arguments: " +vargs.length); for (int arg : vargs) { System.out.println("Value "+arg); } } static void vardisplay(String... vargs) { System.out.println("Inside method with String varargs"); System.out.println("Length of arguments: " +vargs.length); for (String arg : vargs) System.out.println(arg); } public static void main(String args[]) { vardisplay(1, 2); // will compile and run //vardisplay(); // Give compile time error. vardisplay("Delhi","Calcutta", "Banglore"); // will compile and run } } |
Output
Inside method with int Varargs
Length of arguments: 2
Value 1
Value 2
Inside method with String varargs
Length of arguments: 3
Delhi
Calcutta
Banglore
How To covert Varargs into array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.j2eereference.varargs; public class VarargsDemo { public static void varDisplay(int...args) { int[] vartoarray=args; System.out.println("Elements in array is:"); for (int i = 0; i < args.length; i++) { int arr=vartoarray[i]; System.out.println(arr); } } public static void main(String[] args) { varDisplay(100,101,102,103,104,105,106); } } |
Output is:Elements in array is:
100
101
102
103
104
105
106
[…] the second case we are passing parameter through varargs , Click here to know more about varargs in […]