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.
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
}
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);}}
for
loopclass 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);}}
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.for each
loop cannot iterate over an array in reverse.for each
loop is limited to a single step per iteration.for each
loop does not keep track of the current index of the array it’s iterating over.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.