Programming Tutorials

do-while loop in java

By: Jagan in Java Tutorials on 2007-09-07  

If the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do {
// body of loop
} while (condition);

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java's loops, condition must be a Boolean expression. Here is a reworked version of the "tick" program that demonstrates the do-while loop. It generates the same output as before.

// Demonstrate the do-while loop.
class DoWhile {
    public static void main(String args[]) {
        int n = 10;
        do {
            System.out.println("tick " + n);
            n--;
        } while (n > 0);
    }
}

The loop in the preceding program, while technically correct, can be written more efficiently as follows:

do {
System.out.println("tick " + n);
} while(--n > 0);

In this example, the expression (--n > 0) combines the decrement of n and the test for zero into one expression. Here is how it works. First, the --n statement executes, decrementing n and returning the new value of n. This value is then compared with zero. If it is greater than zero, the loop continues; otherwise it terminates.

The do-while loop is especially useful when you process a menu selection, because you will usually want the body of a menu loop to execute at least once. Consider the following program which implements a very simple help system for Java's selection and iteration statements:

// Using a do-while to process a menu selection
class Menu {
    public static void main(String args[])
            throws java.io.IOException {
        char choice;

        do {

            System.out.println("Help on:");
            System.out.println(" 1. if");
            System.out.println(" 2. switch");
            System.out.println(" 3. while");
            System.out.println(" 4. do-while");
            System.out.println(" 5. for\\n");
            System.out.println("Choose one:");
            choice = (char) System.in.read();

        } while (choice < '1' || choice > '5');

        System.out.println("\\n");

        switch (choice) {

            case '1':
                System.out.println("The if:\\n");
                System.out.println("if(condition) statement;");
                System.out.println("else statement;");
                break;
            case '2':
                System.out.println("The switch:\\n");
                System.out.println("switch(expression) {");
                System.out.println(" case constant:");
                System.out.println(" statement sequence");
                System.out.println(" break;");
                System.out.println(" // ...");
                System.out.println("}");
                break;
            case '3':
                System.out.println("The while:\\n");
                System.out.println("while(condition) statement;");
                break;
            case '4':
                System.out.println("The do-while:\\n");
                System.out.println("do {");
                System.out.println(" statement;");
                System.out.println("} while (condition);");
                break;
            case '5':
                System.out.println("The for:\\n");
                System.out.print("for(init; condition; iteration)");
                System.out.println(" statement;");
                break;

        }
    }
}

Here is a sample run produced by this program:

Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);

In the program, the do-while loop is used to verify that the user has entered a valid choice. If not, then the user is re-prompted. Since the menu must be displayed at least once, the do-while is the perfect loop to accomplish this.

A few other points about this example: Notice that characters are read from the keyboard by calling System.in.read(). This is one of Java's console input functions. System.in.read() is used here to obtain the user's choice. It reads characters from standard input (returned as integers, which is why the return value was cast to char). By default, standard input is line buffered, so you must press ENTER before any characters that you type will be sent to your program.

Java's console input is quite limited and awkward to work with. Further, most real-world Java programs and applets will be graphical and window-based. For these reasons, not much use of console input has been made in this book. However, it is useful in this context. One other point: Because System.in.read() is being used, the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors. It is part of Java's exception handling features.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)