You are on page 1of 2

Sample code of a for each loop for some arrays and an ArrayList

For each loop for an integer array and a String array

The line for(int u : numericals) is read as follows


“For each integer (defined as) u in the integer array numericals" ... do something

(Then the code is written to do something with each of the int variables u. In this case it just prints them out.)

As the programmer, you decide the name to be used. As the for-each loop goes through the array, in order, each
integer element in the array is defined as int variable u. There is no index position referenced.
Then that one name is used to represent each element in the array in the rest of the code in the loop.

If that line had instead been typed as follows:


for(int cat : numericals){ then the next line of code following it would have looked like
System.out.print(cat);

In the second example, the same thing is done with the String array called titles.
The programmer decided to represent the strings stored in the array titles with the variable name as his for-each
loop traverses through the code. The loop reads: "For each String (defined as ) name in the String array titles”
Below is an example using a for each loop on an ArrayList
Notice it is very similar to the one used for arrays.

You might also like