In this section we’ll take a look at the four
looping structures in Java, which are all used to execute a code block several times. The while loop runs through the code block
only if the condition is true and will continue looping for as long as the condition remains
true. This loop here will print the numbers 0 to 9. Note that the condition for the loop
is only checked at the beginning of each iteration. Next, there’s the do while loop that works
the same as the while loop, except that it checks the condition after the code block,
and will therefore always runs through the code block at least once. The for loop is used to go through a code
block a specific number of times. It takes three parameters. The first parameters initializes
a counter and is always executed once before the loop. The second parameter holds the condition
for the loop and is checked before each iteration. The third parameter contains the increment
to the counter and is executed at the end of each iteration. The for loop has several
variations. For starters the first and third parameters can be split into several statements
using the comma operator. We also have the option of leaving out either one of the parameters.
For example, we can just as well move the third parameter into the body of the loop. The last looping structure is the foreach
loop which gives an easy way to iterate through arrays. On each loop, the next element in
the array is assigned to the variable – in this case ‘m’ – and the loop continues to
execute until it has gone through the entire array. These are the four looping structures in Java.
Just as the conditional statements the brackets can be left out if there’s only one statement
in the code block. Finally, there are two special keywords that
can be used inside loops. The break keyword which ends the current loop. And continue
which skips the rest of the current loop and continues at the beginning of the next iteration.
If we want to break out of a loop above the current one we must first label that loop,
by adding a name followed by a colon before it. With this in place we can now add the
label as an argument to the break, telling it which loop we want to break out of. This
works the same with the continue keyword, to instead continue on with the next iteration
of the named loop.