Java: For Loop and For-Each Loop


I summarized for loop and for-each loop in Java.

For loop

for loop is a statement to repeat with some condition.

for loop is used with 3 kinds of statements. The first one is an initialization statement (statement 1), the second one is a condition statement for continuing the iteration (statement 2) and the third one is a statement executed after every iteration (statement 3). Each statement can be omitted if it is not needed. If the second statement is omitted, the condition is regarded as true.

Format

If the iteration part can be one statement, { and } can be omitted, as follows.

Example

Here are 2 examples of for loop which iterates with counting up number variable, i. i starts at 0 and after the iteration gets executed 3 times and i becomes 3, the for loop ends.

for-each loop

for-each loop is also used for traversing. It is available for arrays or objects with Iterable interface, and very efficient for them.

Format

Here are the formats of for-each loop.

Compare for loop and for-each loop, with examples

When traversing over an array, for loop requires a variable, the initialization statement, the condition for continuing and the statement executed after each iterating. But for-each loop requires only a variable to hold an element in the array. for-each loop is shorter than for loop.

for loop
for-each loop

As you see, for-each loop can traverse over one array (or one iterable object) in ordinary order easily. It is needless to write initialization statement, continuing condition or procedure after each operation. In that manner, for-each loop requires less description than for loop.

On the contrary, for loop can handle 2 or more arrays at the same time, and can traverse arrays/objects in extraordinary order such as reverse order. Here are examples.

2 arrays example
Reverse order example

To do the same things with for-each loop, creating a new object with Iterable interface is required but that’s a heavier task.

Traverse enum

Come to think of an enum iteration, since enum class can produce an array of itself easily with values method, for-each loop is very efficient for traversing enum, too. Here are for and for-each loop examples over enum.

Thus, using for-each loop for loops in ordinary order makes our program short. In other words, for-each loop decreases bugs, so it is better to use for-each loop as much as we can.