What is for each loop in Java?

The for each loop is another variant of the for loop that iterates over a list or array of elements. The same function is done on each item.

Syntax

The syntax starts out with the standard for keyword followed by parentheses or simple brackets. The brackets contain an object name of some data type followed by a colon followed by an array of the same data type as the declared object.

for (datatype item : array){

   statements using item
}

Code

class ForEach {
public static void main( String args[] ) {
int nums[] = {23, 48, 66, -20, 24, 9, 10};
int max = -9999;
for (int number: nums){
System.out.print(number + " ");
if(max < number)
max = number;
}
System.out.println("\nThe maximum element in the array is " + max);
}
}

Equivalent for loop

class Forloop {
public static void main( String args[] ) {
int nums[] = {23, 48, 66, -20, 24, 9, 10};
int max = -9999;
for (int i = 0; i < nums.length; i++){
System.out.print(nums[i] + " ");
if(max < nums[i])
max = nums[i];
}
System.out.println("\nThe maximum element in the array is " + max);
}
}

Limitations

  1. The for each loop does not modify the contents of the actual array since the iteration object is just a copy of a single array element.
  2. The for each loop cannot iterate over an array in reverse.
  3. The for each loop is limited to a single step per iteration.
  4. The for each loop does not keep track of the current index of the array it’s iterating over.
  5. The for each loop cannot handle multiple decision-making statements at once.

What the for each loop offers is enhanced readability and fewer chances of programming errors.

Free Resources