Java Reference
In-Depth Information
You can write the following snippet of code that will compute the maximum of two and three integers using the
MathUtil3.max() method:
int[] num1 = new int[] {10, 1};
int max1 = MathUtil3.max(num1);
int[] num2 = new int[] {10, 8, 18} ;
int max2 = MathUtil3.max(num2);
You can pass an arbitrary number of integers to the MathUtil3.max() method. In a sense, you have a way to
pass an arbitrary number of arguments to a method. What bothers programmers is the way the method needs to be
called when its argument type is an array. You must create an array object and package the values of all its elements
when you need to call the method with an array argument. The issue here is not the code inside the max(int[] num)
method. Rather, it is the client code that calls this method.
Varargs comes to the rescue. Let's declare a max() method, which can accept any number of integer arguments
including zero arguments. The beauty of a varargs method is in the simpler client code that calls the method. So, how
do you declare a varargs method? All you need to do is to add an ellipsis (or triple-dot like ...) after the data type of
the method's argument. The following snippet of code shows a max() method declaration with one variable-length
argument, num , which is of the int data type. Note the placement of ellipsis after the data type int .
public static int max(int... num) {
// Code goes here
}
Adding whitespaces before and after ellipsis is optional. All of the following varargs method declarations are
valid. They use different whitespaces before and after the ellipsis.
public static int max(int... num) // A space after
public static int max(int ... num) // A space before and after
public static int max(int...num) // No space before and after
public static int max(int ...
num) // A space before and a newline after
A varargs method can have more than one argument. The following snippet of code shows that aMethod()
accepts three arguments, one of which is a variable-length argument:
public static int aMethod(String str, double d1, int...num) {
// Code goes here
}
There are two restrictions for a varargs method:
A varargs method can have a maximum of one variable-length argument. The following
declaration for m1() method is invalid because it declares two variable-length arguments,
n1 and n2 :
// Invalid declaration
void m1(String str, int...n1, int...n2) {
// Code goes here
}
 
Search WWH ::




Custom Search