Java Reference
In-Depth Information
On the other hand, you should leave the following for loop as is and not attempt to
convert it to a for-each loop:
for ( int i = 0; i < a.length; i++)
a[i]= 2*i;
Because this for loop uses the index i in the body of the for loop and uses it in an
essential way, it does not make sense to convert this for loop to a for-each loop.
For-Each Loop for Arrays
SYNTAX
for ( Array_Base_Type Variable : Array_Name )
Statement
EXAMPLES
for ( double element : a)
sum += element;
The array a has base type double . This for-each loop sets each element of the array a
to 0.0 .
A good way to read the first line of the example is “For each element in a , do the following.”
Methods with a Variable Number of Parameters
Because of overloading, you can have a method named max that returns the largest of
two int values and have another method named max that takes three int arguments
and returns the largest of the three. If you decide you need a method that returns the
largest of four int values, you can define a version of the method max that takes four
arguments. However, with this approach, there is no way to cover all cases of computing
the maximum of some number of int values. Covering all cases in this way would
require an infinite number of definitions for the method name max , and no programmer
has enough time to write an infinite number of definitions. What we would like is a
single method definition for a method named max that can take any number of int
arguments. Starting with version 5.0, Java lets you define methods that take any number
of arguments. For example, the following is the definition of a method named max that
takes any number of int arguments and returns the largest of its arguments:
public static int max( int ... arg)
{
if (arg.length == 0)
{
System.out.println("Fatal Error: "+
"maximum of zero values.");
System.exit(0);
}
 
Search WWH ::




Custom Search