The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search

Trail: Learning the Java Language
Lesson: The Nuts and Bolts of the Java Language

## The while and do-while Statements

> You use a `while` statement to continually execute a block of statements while a condition remains true. The general syntax of the `while` statement is:

> >     while (expression) {
> >         statement
> >     }

> First, the `while` statement evaluates expression, which must return a boolean value. If the expression returns true, then the `while` statement executes the statement(s) associated with it. The `while` statement continues testing the expression and executing statements until the expression returns false.

> The example program shown below, called `WhileDemo`, uses a `while` statement to iterate over a string, copying the characters from the string into a string buffer until it encounters the letter 'g'.

> >     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);
> >         }
> >     }

> Java provides another statement that is similar to the `while` statement--the `do`-`while` statement. The general syntax of the `do`-`while` is:

> >     do {
> >         statement
> >     } while (expression);

> Instead of evaluating the expression at the top of the loop, `do`-`while` evaluates the expression at the bottom. Thus the statements associated with a `do`-`while` are executed at least once.

> Here's the previous program re-written to use `do`-`while` and renamed to `DoWhileDemo`:

> >     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);
> >         }
> >     }

| Start of Tutorial > Start of Trail > Start of Lesson | Search