for each

for each

A for each loop(or enhanced for loop) is used to traverse a array, but they can’t change the values of elements with a primitive datatype because the variable given refers to a element that holds a copy of the element.

A for each loop is made like ;

for( data/objectTypeOfTheElementsInTheArray varName : ArrayName)

{

. . . //process varName

}

Also do not use a for each loop if you need to access the indices, because the example above is basically equal to:

for( int i =0; i<arrayName.length;i++)

{

data/objectTypeOfTheElementsInTheArray varName = arrayName[ i ];

. . . //process varName

}

A common use of for each loops include finding the arrays smallest or largest value.

3 thoughts on “for each

Comments are closed.