It is not necessary to iterate through array elements using a loop only
for
. There is a more compact design for each
, an example of which is given below.
int[] elements = { 1, 2, 3, 4, 5 };
for (int k : elements) {
System.out.println(k);
}
In parentheses we indicate that we are iterating over the elements of the array elements
, and the variable k
is the next element of this array at the next iteration. Naturally, the types of the variable and the array must match. In the body of the loop we indicate processing operators. In this example, we simply print all the elements of the array to the console.
GO TO FULL VERSION