JavaRush /Java Blog /Random EN /for each vs for: usage scenarios

for each vs for: usage scenarios

Published in the Random EN group
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 kis 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.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION