OCA Java SE 8 Operators/Statements - Java while Statement

A repetition control structure executes a statement of code multiple times in succession.

The while statement has a termination condition, implemented as a boolean expression, that will continue as long as the expression evaluates to true.

Curly braces required for block of multiple statements, optional for single statement

while(booleanExpression) { 

A while loop is similar to an if-then statement in that it is composed of a boolean expression and a statement, or block of statements.

The boolean expression is evaluated before each iteration of the loop and exits if the evaluation returns false.

A while loop may terminate after evaluation of the boolean expression for the first time. In this manner, the statement block may never be executed.

Infinite Loops

Consider the following segment of code:

The boolean expression that is evaluated prior to each loop iteration is never modified, so the expression (x < 10) will always evaluate to true.

The result is that the loop will never end.

int x = 1; 
int y = 1; 
while(x < 10) 

do-while Statement

A do-while loop is a repetition control structure with a termination condition and statement, or block of statements.

A do-while loop guarantees that the statement or block will be executed at least once.

Curly braces required for block of multiple statements, optional for single statement.

do { 

} while (booleanExpression);                                       

For example, take a look at the output of the following statements:

int x = 0; 
do { 
} while(false); 
System.out.println(x);  // Outputs 1 

Java will execute the statement block first, and then check the loop condition.