Java For Each Loop Syntax
Java does not have a foreach key word like some other programming languages do. Instead, it has an enhanced for loop that accomplishes the same thing. The syntax is as follows:
for(type itr-var : collection) statements
“Type” is what it says it is. It is the type for the itr-var.
“Itr-var” is the iteration variable. It will hold each member of the collection as you iterate through the loop.
“Collection is the collection of objects you’re cycling through.
Let’s say you have an array of numbers call nums. An array is a collection. So let’s say you want to iterate through that collection. Your for each loop would look like this:
for(int x : nums)
Think of it like this: “For each int x in the collection nums do…” The statements inside the code block following the “for-each” are automatically executed.