Java Reference
In-Depth Information
The above logic works fine. It computes the maximum of two integers, and then computes the maximum of the
two and the third integer. Suppose you want to compute maximum of ten integers. You might repeat the above logic
and that will work, although the code may not be readable. You need a better way of doing this.
Let's try overloading the max() method, so it accepts three integer arguments. Here is the newer version of the
MathUtil class, called MathUtil2 :
public class MathUtil2 {
public static int max(int x, int y) {
int max = x;
if (y > max) {
max = y;
}
return max;
}
public static int max(int x, int y, int z) {
int max = x;
if (y > max) {
max = y;
}
if (z > max) {
max = z;
}
return max;
}
}
You can compute maximum of two and three integers as
int max1 = MathUtil2.max(12, 18);
int max2 = MathUtil2.max(10, 8, 18);
Adding a max() method with three int arguments did solve the problem temporarily. The real problem still
remains. You will have to add a max() method with all possible number of integer arguments. You would agree that no
programmer wants to write a max() method where he will have to keep adding a newer version.
Before Java 5, when the number of arguments of a method was not known at design time, you would declare the
method argument as an array of int , as shown below. I will discuss arrays in detail in chapter 15.
public class MathUtil3 {
public static int max(int[] num) {
/* Must check for zero element in num here */
int max = Integer.MIN_VALUE;
for(int i = 0; i < num.length; i++) {
if (num[i] > max) {
max = num[i];
}
}
return max;
}
}
 
Search WWH ::




Custom Search