The while loop
The while loop allows programs to repeat a statement or series of statements, over and over, as long as a certain test condition is true.  The format is shown in the box to the right.

The test condition must be enclosed in parentheses.  The block of code is known as the body of the loop and is enclosed in braces and indented for readability.  (The braces are not required if the body is composed of only ONE statement.)  Semi-colons follow the statements within the block only.

When a program encounters a while loop, the test condition is evaluated first.  If it is TRUE, the program executes the body of the loop.  The program then returns to the test condition and reevaluates.  If still TRUE, the body executes again.  This cycle of testing and execution continues until the test condition evaluates to FALSE.  If you want the loop to eventually terminate, something within the body of the loop must affect the test condition.  Otherwise, a disastrous INFINITE LOOP is the result!  In Eclipse, you can cancel (stop) an infinite loop by clicking on the Terminate button on the right side of the Console window.

The while loop is an entry-condition loop.  If the test condition is FALSE to begin with, the program never executes the body of the loop.

Similar to the "if" statement, any variable declared in the block for a while loop has block scope. They will not be recognized by coding outside of the block

The following program fragment prints the characters of a string (one per line) and counts the total number of characters of the string:

String name="Corky";
int i = 0;
//begin with the first cell of string
while (i < name.length( ))
// loop test condition
{
    
//print each cell on a new line
     System.out.println(name.charAt(i));
     i++;             //increment counter by 1
}
System.out.println("There are "+ i + " characters.");
/*This last statement prints when the test condition is false and the loop terminates - finishes.*/ 
FORMAT:
while(test condition)
{
     block of code;
}



computerdogs



roundarrow

iteration - doing the same thing again and again.



terminate



Check out the Demo "while" loop fragments.

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Copyright © 1998 - 2024 JavaMathBits.com. All Rights Reserved.