A for-each style loop can loop through a collection of objects, such as an array.
The for-each loop is also called the enhanced for loop.
The general form of the for-each loop:
for(type itr-var : collection){ statement-block }
Here, type
specifies the type and itr-var
specifies the name of an iteration variable.
itr-var
will receive the elements from a collection, one at a time, from beginning to end.
The following code uses a traditional for loop to compute the sum of the values in an array:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int i=0; i < 10; i++){ sum += nums[i]; }
The follow code uses a for-each loop:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int x: nums){ sum += x; }
Here is an entire program that demonstrates the for-each loop:
// Use a for-each style for loop. public class Main { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use for-each style for to display and sum the values for(int x : nums) { System.out.println("Value is: " + x); sum += x; /* w w w . j a v a2 s .c om*/ } System.out.println("Summation: " + sum); } }
The for-each loop variable is "read-only".
Updating to the iteration variable has no effect on the underlying collection.
For example, consider this program:
// The for-each loop is essentially read-only. public class Main { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for(int x : nums) { System.out.print(x + " "); x = x * 10; // no effect on nums } //from w w w . ja v a 2s. co m System.out.println(); for(int x : nums) System.out.print(x + " "); System.out.println(); } }