for-each loop

Definition

A for-each loop is used to iterate over an array. This means that it will perform one thing using (but not changing- see Important) each index in the array.

Benefits

A for-each loop is simple to read, as it avoids confusing initializations and conditions. It also prevents off-by-one errors and confused logic notation.

Format

The format of a for-each loop is as follows:

for(type : set) {
  //code here
}

Example

The following code prints the height in centimeters of each boy in Arnie's class using array inch, which contains their heights in inches.

int[] inch = {49, 52, 52, 54, 55, 55, 57};
for(int x : inch) {
   System.out.print(x * 2.54 + "\t");
}

In the above code, x essentially moves up the array each time the loop runs, until the array is finished.

Important

The for-each loop is essentially read only. It cannot be used to adjust, add or remove elements in an array.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License