Thursday, August 4, 2016

JAVA For - Each Loops



When working with arrays,  a for - each loop can be very helpful. The process of stepping through each component of an array with a for loop is so common that a simplified version of that process was created using the for - each loop.


The general format of the for - each loop looks like:


for ( type variable : arrayName) {
statements using variable;
}

The variable type must be the same type as the array and represents the current array component that the loop is counting through.

This loop automatically repeats the same number of times as the number of array components, or the total array length.

This type of loop can save time and space when dealing with arrays. For example, computing the average values of an array is simplified to look like:


int sumArray =0;

for( int i : averageArray) {
sumArray+ = i;
}

double average= (double)sumArray/averageArray.length;



You can use the for - each loop for other types of JAVA collections

Do Not Use for - each loops when you want to modify an array

Do Not Use for - each loops to return a components index/location

Do Not Use for-each loops if you want to step through an array by values other than +1

Do Not Use for - each loops if you want to process information on more than one loop at once


No comments:

Post a Comment