Learning Java
Custom Search

Previous Next

while Loop

The "while" keyword is used to set up a loop to repeatedly execute the statements in its range until a certain condition is met, similar to the for loop. However, in the parentheses after the keyword "for", we had 3 phrases. Within the parentheses of the "while" loop, we only have the one phrase describing the condition. Use brackets { } when you want to execute more than one statement in the loop.

	while (this is true) {
	    execute this step 1;
	    execute this step 2;
	    execute this step 3;
	}

do..while Loop

The "do..while" loop is similar to the while loop, except the condition is tested after the statements within are executed. Thus, the statements will be executed at least once.

	do {
	    execute this step 1;
	    execute this step 2;
	    execute this step 3;
	} while (this is true);

In the following example, we have the same code in both a "while" and a "do..while" statement. You will see that they produce about the same results.

class WhileTest {

    public static void main(String args[]) {

	int y = 10;
	while (y > 0) {
	    y = y - 2;
	    System.out.println("while:  y=" + y);
	}
	System.out.println("----------");

	y = 10;
	do {
	    y = y - 2;
	    System.out.println("do:  y=" + y);
	} while (y > 0);
    }
}

In the 2 places where y = 10, change it to y = 0 and retest. In this case the while condition starts out as being false. The "while" loop does not execute, but the "do..while" executes once.

	int y = 0;

	y = 0;

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved