Syntax 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:

  1. How many times was the condition true? 3
  2. How many times did the block statement following the while execute? 3

Syntax of the while statement

Here is the syntax for the while statement:

while ( condition )
  statement 

Notes:

  • The condition is a Boolean expression: something that evaluates to true or false.
  • The condition can be complicated, using many relational operators and logical operators.
  • The statement is a single statement. However it can be (and usually is) a block statement containing several other statements.
  • The statement is sometimes called the loop body.

Since the statement can be a single statement or a block statement, a while statement looks like either of the following:

Varieties of while Statements

while ( condition )
  statement;

while ( condition )
{
  one or more statements
}

The style of indenting used here leads to fewer errors than alternative styles.

QUESTION 5:

Is the condition always surrounded by parentheses?