Varargs Method
A method is called varargs method when it can take a variable number of arguments as its parameters. The arguments should be of same data type. The all arguments combined is called as variable-length argument and is specified by three dots (...). And in the method, the argument is accessed as an array.
Here is the example of the method definition -
Test(int ... num) {for(int i = 0; i < num.length; i++) {System.out.println(num[I]);}}
And to call method, you can pass variable number of values of int data type -
Test(3, 4, 5);Test(2, 4, 6, 8, 10);
The varargs method can have arguments more than one, but there can be only one variable-length argument and it should be the last argument passed to the method. Here are the examples of valid varargs method declaration -
Test(boolean a, int ... num) ✓
Test(int a, float b, int ... num) ✓Test(boolean ... a) ✓
These are invalid method declaration examples, -
Test(int ... num, float b, int a) ✗
Test(boolean a, int ... num, float y) ✗
Overloaded Varargs Methods
Varargs method can be overloaded too. Like I mentioned examples of valid varargs methods above, when used in a program they are considered as overloaded methods -
Test(boolean a, int ... num)
Test(int a, float b, int ... num)Test(boolean ... a)
Ambiguous Overloaded Varargs Methods
Sometimes overloaded varargs methods are syntactically fine but show ambiguity. Following example shows ambiguity when the program calls the overloaded method without any arguments, the program will not compile. -
Test(int ... num)
Test(boolean ... a)
And call the method Test() without arguments, compiler won't be able to know which method should be called when there are no arguments passed to the method -
Test();
Here is another example of overloaded varargs method which shows ambiguity. The compiler won't be able to resolve which method should be called -
Test(int ... num)
Test(int a, int ... num)
Example of use of Varargs method to get maximum of given numbers
public class MaxVal {
public static void main(String args[]) {
int a = max(10, 20, 30);
int b = max(25, 35, 37, 28, 25);
int c = max(1, 12, 33, 23, 45, 19, 34, 64, 28);
System.out.println("Max Values are : a = " + a + ", b = " + b + ", c = " + c);
}
public static int max(int ... num) {
int m = num[0];
for(int i = 1; i < num.length; i++) {
if(num[i] > m) m = num[i];
}
return m;
}
}
No comments:
Post a Comment