Lesson 2


A loop allows you to execute a statement or block of statements repeatedly. The need to repeat a block of code arises in many programs. Listed below are ways to accomplish this in Java:

The while loop

    // statements

This loop executes as long as a given logical expression is true. When the expression is false, execution continues with the statement following the loop block. The expression is tested at the beginning of the loop, so if it is initially false, the loop statement block will not be executed at all.

The do-while loop

    // statements
} while(expression);

This loop is similar to the while loop, except that the expression controlling the loop is tested at the end of the
loop block. This means that the loop block is executed at least once, even if the expression is initially false.
There are situations where you may want to skip all or part of a loop iteration. Suppose we want to sum the values of the integers from 1 to some limit, except that we don't want to include integers that are multiples of three. We can do this using an if and a continue statement:

The for loop

for(int i = 1; i <= limit; i++)
     if(i % 3 = = 0)
       continue; // Skip the rest of this iteration
     sum += i; // Add the current value of i to sum

The continue statement is executed in this example when i is an exact multiple of 3. It causes the rest of the current loop iteration to be skipped. Program execution continues with the next iteration if there is one, and if not, with the statement following the end of the loop block. The continue statement can appear anywhere within a block of loop statements. You may even have more than one continue in a loop.

Control Flow Statements

Statements such as the while statement are control flow statements. They determine the order in which other statements are executed. The Java language supports several other control flow statements:

Statement    Keyword
decision making     if-else, switch
loops     for, while, do-while
exceptions     try-catch-throw   (See Lesson 13)
miscellaneous     break, continue, label:, return

Although goto is a reserved word, the Java language does not support the goto statement.

Below is a program that demonstates a loop in Java:

Assignment 2

- Write an an applet that takes the square root of a number - Use an array to store the square roots of the numbers 2 to 15.

Return to the Top