Iteration Statements

Programmers use iteration statements to control sequences of statements that are repeated according to runtime conditions.

Java supports three types of iteration statements:

  • while

  • do

  • for

while Loops

The while statement tests an expression and, if it's true, executes the next statement or block repeatedly until the expression becomes false. When the variable or expression is false, control is passed to the next statement after the while statement. The syntax for a while loop looks very similar to that of an if statement:

while (expression)
  statement;

The following example shows a while loop in action:

 boolean done = false; // read characters from the keyboard until an x is typed while (!done) { int c = System.in.read(); ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.