Control flow statements – for loop

When it comes to iterate over a set of values ​​in Java the for loop is one of the most, if not the most, used approaches. A for loop begins with an expression that consists of three parts: initialization of a variable, termination – ie. for how long the loop should continue, and an incremental or decremental part that shows by how much the original value will increase or decrease each time in the loop.

This is an example of a for loop:

In the above example we can see that a variable named i is declared with the value of 0. This is followed by a semi-colon which marks the end of the first part. The second path shows for how long the loop shall continue. It is told to continue for as long as i is less than or equal to 10. The third part shows by how much the value of variable i should increase for each time in the loop. i++ means that variable i will be incremented by one each time (i++ is equivalent to writing i = i + 1, see section about operators for more).

The output from the above code would be:

Even if none of the three parts in the for loop is mandatory the most common case is to use all three since you would otherwise easily end up with an endless loop. Consider the following changes from the example above:

    - In the first example we omit the last part so the variable i is never incremented. This means that it will print out the value 0. Forever.
    - In the second example we omit the second part so the loop doesn’t know when to stop. It will print out an incremented value each time it runs. Forever.
    - In the third example all three parts are omitted so we can’t output variable i since it’s not declared. It will instead print out the text ‘looping forever’. Yes…forever.

Arrays and Collections

If we want to loop through an array we can use a simpler variant of the for loop that consists of only two parts. By just declaring the variable (which must be of the same data type as the elements of the array) and the array variable we can loop through it. The two parts are separated with a colon instead of a semi-colon as they were in the examples above. The for loop assumes that it shall start on the first position in the array and then the next position etc. until the end of the array is reached. Here’s how it looks like:

With the output:

The same technique can be applied to a List, or any Collection objects. In this case a list of strings:

With the results of course:

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?