Java Reference
In-Depth Information
The body of the MathUtil4.max() method is exactly the same as if the num argument is declared as an int array.
You are right in thinking so. The Java compiler implements a variable-length argument of a method using an array.
The above declaration of the MathUtil4.max() method is changed by the compiler. The declaration part
max(int...num) is changed to max(int[] num) when you compile the code. What benefit do you get using a
variable-length argument? The benefit of using a variable-length argument in a method comes from the elegant way
of calling the method. You can call the MathUtil4.max() method as follows:
int max1 = MathUtil4.max(12, 8);
int max2 = MathUtil4.max(10, 1, 30);
You can use zero or more arguments for a variable-length argument in a method. The following code is a valid
call to the max() method:
int max = MathUtil4.max(); // Passing no argument is ok
What will be returned by calling the MathUtil4.max() method with no argument? If you look at the method's
body, it will return Integer.MIN_VALUE , which is -2147483648 . Practically, a call to the max() method without at
least two arguments is not a valid call. You must check for invalid number of arguments when a method is a varargs
method. You do not get a problem of invalid number of arguments for non-varargs methods because the compiler will
force you to use the exact number of arguments. The following declaration of the max() method will force its caller to
pass at least two integers:
// Argumenets n1 and n2 are mandatory
public static int max(int n1, int n2, int... num) {
// Code goes here
}
The compiler will treat the first two arguments, n1 and n2 , as mandatory and the third argument, num , as optional.
Now, you can pass two or more integers to the max() method. Listing 6-34 shows the final, complete code for the
max() method.
Listing 6-34. A Utility Class to Compute the Maximum of Some Specified Integers Using a Varargs Method
// MathUtil5.java
package com.jdojo.cls;
public class MathUtil5 {
public static int max(int n1, int n2, int... num) {
// Initialize max to teh maximu of n1 and n2
int max = (n1 > n2 ? n1 : n2);
for(int i = 0; i < num.length; i++) {
if (num[i] > max) {
max = num[i];
}
}
return max;
}
 
Search WWH ::




Custom Search