New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.


Get the latest Java books
h t t p : / /w w w . j a v a c o f f e e b r e a k . c o m /

Java Coffee Break

Menu



Learning Java

Articles
Author Profiles
Lessons
FAQ's
Books
Newsletter
Tutorials
Talk Java!

Using Java

Applets
JavaBeans
Servlets
Resources
Discuss Java


Looking for Java resources? Check out the Java Coffee Break directory!

Is Java driving you loopy?

If Java is your first programming language, then loops (a form of iteration) can be a confusing topic. In this article, I'll show you the different types of loops that Java supports, and when to use them. -- David Reilly

There are three basic building blocks of programming :-

  • sequence

  • selection

  • iteration

Most programmers will be familiar with sequence. A sequence of programming statements are executed one after the other. For example, the following two lines can be executed sequentially

System.out.println ("hello");
System.out.println ("goodbye");

Selection is also fairly simple. By using if / switch statements, you can control the execution flow of code. Most programmers are already familiar with the concept behind if statements - it is virtually impossible to write any application without using some form of selection.

The final concept, iteration, is the focus of this article. This one is a little more tricky, as there are quite a few different times of iteration statements in Java. The basic concept behind iteration, is that a sequence of statements is repeated until a certain condition is met. When this condition is met, the iteration terminates, and the loop is over.

'for' loops

The simplest type of loop uses the for statement, to iterate through a sequence of statements. Usually, a for loop will use a counter, with a precise starting point and a precise ending point.

// for loop, from 1 to 5
for (int i = 1; i <= 5; i++)
{
    System.out.println ("count : " + i);
}

There are several components to a for loop

for ( init    condition   ;   statement ) 

A check to see if the condition equates to true is made at the end of the for loop. When the condition fails to be met, the loop will terminate. In our previous example, the loop terminates when our counter (i) is not less than or equal to a value of five.

It is also worth noting that each of the components of a for loop is entirely optional. For example, our loop could be rewritten as the following: -

// This may be more useful, as the variable
// i is created outside the scope of the 
// loop.
int i = 1;
// for loop, from i to 5
for (; i <= 5; i++)
{
    System.out.println ("count : " + i);
} 

'while' loops

A while loop differs from the for loop, in that it only contains a condition, and that the condition is tested at the beginning of the loop. This means that if the condition evaluates to false, it will not be executed at all. We call this a pre-tested loop, because the test is made before executing the sequence of statements contained within.

int i = 1;

while (i <= 5)
{
    System.out.println ("count : " + i);
    i++;
}

'do...while' loops

A variation on the while loop is the post-tested version. Two keywords are used for this loop, the do and the while keywords.

int i = 1;

do
{
    System.out.println ("count : " + i);
    i++;
}
while (i <= 5)

There is no difference between a while, and a do...while loop other than pre-testing and post-testing.

Terminating loops abruptly

Sometimes it is necessary to stop a loop before its terminating condition is reached. For example, a loop that searched through an array for a particular entry should not continue once that entry is found - to do so would only waste CPU time and make for a slower program. Other times, you may want to skip ahead to the next iteration of the loop, rather than performing additional processing. Java provides two keywords for this purpose : break and continue

break

The break keyword is used to terminate a loop early. Consider the following example, which searches through an array for a particular value.

// Check to see if "yes" string is stored
boolean foundYes = false;

for (int i = 0; i < array.length; i++)
{
    if (array[i].equals("yes"))
    {
        foundYes = true;
        break;
    }
}

continue

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

for (int i = 0; i < array.length; i++)
{
    if (array[i] == null)
        // skip this one, goto next loop
        continue;
    else
    {
        // do something with array[i]
        .......
    }
}

While this example was unnecessary, since we had an if statement to separate program flow, there are some complex algorithms where continue and break are extremely useful.

Summary

Loop don't need to be difficult, providing you keep in minds these simple concepts: -

  • loops are for repetition of statements

  • some loops are pre-tested (for, while), others are post-tested (do..while)

  • when you have a clearly defined start and finish, a for loop is preferable

  • when you have a more complex termination condition, while loops are preferable

Back to main


Copyright 1998, 1999, 2000 David Reilly

Privacy | Legal | Linking | Advertise!

Last updated: Monday, June 05, 2006