Java Reference
In-Depth Information
int largest = arg[0];
for ( int i = 1; i < arg.length; i++)
if (arg[i] > largest)
largest = arg[i];
return largest;
}
This method max works by taking its int arguments and placing them in an array
named arg whose base type is int . For example, suppose this definition of the method
max is in a class named UtilityClass , and consider the following method call:
int highestScore = UtilityClass.max(3, 2, 5, 1);
The array arg is automatically declared and initialized as follows:
int [] arg = {3, 2, 5, 1};
So, arg[0] == 3, arg[1] == 2, arg[2] == 5 , and arg[3] == 1 . After this, the
code in the body of the method definition is executed. Display 6.7 shows a sample
program that uses this method max .
Note that a method (such as max ) that takes any number of arguments is basically a
method that takes an array as an argument, except that the job of placing values in the
Display 6.7
Method with a Variable Number of Parameters (part 1 of 2)
1 public class UtilityClass
2 {
3 /**
4 Returns the largest of any number of int values.
5 */
6 public static int max( int ... arg)
7 {
8 if (arg.length == 0)
9 {
10 System.out.println("Fatal Error: maximum of zero values.");
11 System.exit(0);
12 }
13 int largest = arg[0];
14 for ( int i = 1; i < arg.length; i++)
15 if (arg[i] > largest)
16 largest = arg[i];
17 return largest;
18 }
19 }
20
This is the file UtilityClass.java
(continued)
 
Search WWH ::




Custom Search