Java Reference
In-Depth Information
public static void main(String[] args) {
System.out.println("max(7, 9) = " + MathUtil5.max(7, 9));
System.out.println("max(70, 19, 30) = " + MathUtil5.max(70, 19, 30));
System.out.println("max(-7, -1, 3) = " + MathUtil5.max(-70, -1, 3));
}
}
max(7, 9) = 9
max(70, 19, 30) = 70
max(-7, -1, 3) = 3
You can pass any number of integers when you call the MathUtil5.max() method. All of the following statements
are valid:
int max1 = MathUtil5.max(12, 8); // will return 12
int max2 = MathUtil5.max(10, 1, 30); // will return 30
int max3 = MathUtil5.max(11, 3, 7, 37); // will return 37
If you call the MathUtil5.max() method with no arguments or one argument, the compiler will generate an error.
int max1 = MathUtil5.max(); // A compile-time error
int max2 = MathUtil5.max(10); // A compile-time error
Overloading a Varargs Method
The same overloading rules for methods also apply to a varargs method. You can overload a method with a variable-
length argument as long as the parameters for the methods differ in type, order, or number. For example, the following
is a valid example of an overloaded max() method:
public class MathUtil6 {
public static int max(int x, int y) {
// Code goes here
}
public static int max(int...num) {
// Code goes here
}
}
Consider the following snippet of code, which calls the overloaded method MathUtil6.max() with two
arguments:
int max = MathUtil6.max(12, 13); // which max() will be called?
The MathUtil6 class has two max() methods. One method accepts two int parameters and another accepts a
variable-length int parameter. In the above case, Java will call the max(int x, int y) . Java first attempts to find a
method declaration using an exact match for the number of parameters. If it does not find an exact match, it looks for
a match using variable-length parameters.
 
Search WWH ::




Custom Search