The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

The while and do-while Statements

You use a while (in the glossary) statement to continually execute a block of statements while a condition remains true. The following is the general syntax of the while statement.
while (expression) {
    statement
}
First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression returns false.

The following example program, called WhileDemo (in a .java source file), uses a while statement (shown in boldface) to step through the characters of a string, appending each character from the string to the end of a string buffer until it encounters the letter g. You will learn more about the String and StringBuffer classes in the next chapter, Object Basics and Simple Data Objects (in the Learning the Java Language trail).

public class WhileDemo {
    public static void main(String[] args) {

        String copyFromMe = "Copy this string until you " + 
                            "encounter the letter 'g'.";
        StringBuffer copyToMe = new StringBuffer();

        int i = 0;
        char c = copyFromMe.charAt(i);

        while (c != 'g') {
            copyToMe.append(c);
            c = copyFromMe.charAt(++i);
        }
        System.out.println(copyToMe);
    }
}
The value printed by the last line is Copy this strin.

The Java programming language provides another statement that is similar to the while statement — the do-while (in the glossary) statement. This is the general syntax of do-while.

do {
    statement(s)
} while (expression);
Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at the bottom. Thus, the statements within the block associated with a do-while are executed at least once.

Here's the previous program rewritten to use do-while (shown in boldface) and renamed to DoWhileDemo (in a .java source file).

public class DoWhileDemo {
    public static void main(String[] args) {

        String copyFromMe = "Copy this string until you " +
                            "encounter the letter 'g'.";
        StringBuffer copyToMe = new StringBuffer();

        int i = 0;
        char c = copyFromMe.charAt(i);

        do {
            copyToMe.append(c);
            c = copyFromMe.charAt(++i);
        } while (c != 'g');
        System.out.println(copyToMe);
    }
}
The value printed by the last line is Copy this strin.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.