News & UpdatesProgrammingWeb programming StoreMy Projects

Java Tutorial – 09 – Loops

There are four looping structures in Java. These are used to execute a specific code block multiple times. Just as with the conditional if statement, the curly brackets for the loops can be left out if there is only one statement in the code block.

While loop

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. The loop below will print out the numbers 0 to 9.

int i = 0;
while (i < 10) { System.out.print(i++); }

Note that the condition for the loop is only checked at the start of each iteration (loop).

Do-while loop

The do-while loop works the same way as the while loop, except that it checks the condition after the code block. It will therefore always run through the code block at least once. Bear in mind that this loop ends with a semicolon.

int i = 0;
do { System.out.print(i++); } while (i < 10);

For loop

The for loop is used to go through a code block a specific number of times. It uses three parameters. The first parameter 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 of the counter and is executed at the end of each iteration.

for (int i = 0; i < 10; i++) { 

The for loop has several variations. For instance, the first and third parameters can be split into several statements by using the comma operator.

for (int k = 0, l = 10; k < 10; k++, l--) { 
  System.out.print(k + l); 

There is also the option of leaving out one or more of the parameters. For example, the third parameter can be moved into the body of the loop.

for (int k = 0, l = 10; k < 10;) { 
  System.out.print(k + l); k++; l--; 

Foreach loop

The foreach loop provides an easy way to iterate through arrays. At each iteration the next element in the array is assigned to the specified variable, and the loop continues to execute until it has gone through the entire array.

int[] array = { 1,2,3 };
for (int element : array) { 

Break and continue

There are two special keywords that can be used inside loops – break and continue. The break keyword ends the loop structure, and continue skips the rest of the current iteration and continues at the start of the next iteration.

break;    // end current loop
continue; // start next iteration

To break out of a loop above the current one, that loop must first be labeled by adding a name followed by a colon before it. With this label in place it can now be used as an argument to the break statement, telling it which loop to break out of. This also works with the continue keyword in order to skip to the next iteration of the named loop.

myLoop: for (int i = 0, j = 0; i < 10; i++) 
          while (++j < 10)
            break myLoop;    // end for
            continue myLoop; // start next for                

Labeled block

A labeled block, also called a named block, is created by placing a label before an anonymous code block. The break keyword can be used to break out of such a block, just as in labeled loops. This could for example be useful when performing a validation, where if one validation step fails the whole process must be aborted.

    break validation;

Labeled blocks can be useful for organizing a large method into sections. In most cases though, splitting the method up is a better idea. However, if the new method would require a lot of parameters, or if the method would only be used from a single location, then one or more labeled blocks may be preferable.

Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours