Semantics of the while statement

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Yes.

Semantics of the while statement

Here is the while statement, again:

while ( condition )
  loop body            // a statement or block statement

statement after the loop

Some notes on the semantics:

  • When control reaches the while the condition determines if the loop body executed.
  • When the condition is true, the loop body is executed. After the loop body is executed, control is sent back to the while, which again evaluates the condition.
  • When the condition is false, the loop body is skipped. Control is sent to whatever statement follows the loop body.
  • Once execution has passed to the statement after the loop, the while statement is finished, at least for now.
  • If the condition is false the very first time it is evaluated, the loop body will not be executed even once.

Here is the while loop from the example program:

int count = 1;                                  // start count out at one
while ( count <= 3)                             // loop while count is <= 3
{
  System.out.println( "count is:" + count );
  count = count + 1;                            // add one to count
}
System.out.println( "Done with the loop" );     // statement after the loop

This loop makes use of the variable count. It is started out at 1, then incremented by one until the condition is false. Then the statement after the loop is executed.

QUESTION 6:

The variable count is used in three different activities. It is initialized, tested, and changed. Where in the program does each of these events take place?