Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 195

The while Statement

Оглавление

The simplest repetitive control structure in Java is the while statement, described in Figure 3.5. Like all repetition control structures, it has a termination condition, implemented as a boolean expression, that will continue as long as the expression evaluates to true.

FIGURE 3.5 The structure of a while statement

As shown in Figure 3.5, a while loop is similar to an if statement in that it is composed of a boolean expression and a statement, or a block of statements. During execution, the boolean expression is evaluated before each iteration of the loop and exits if the evaluation returns false.

Let's see how a loop can be used to model a mouse eating a meal:

int roomInBelly = 5; public void eatCheese(int bitesOfCheese) { while (bitesOfCheese> 0 && roomInBelly> 0) { bitesOfCheese--; roomInBelly--; } System.out.println(bitesOfCheese+" pieces of cheese left"); }

This method takes an amount of food—in this case, cheese—and continues until the mouse has no room in its belly or there is no food left to eat. With each iteration of the loop, the mouse “eats” one bite of food and loses one spot in its belly. By using a compound boolean statement, you ensure that the while loop can end for either of the conditions.

One thing to remember is that a while loop may terminate after its first evaluation of the boolean expression. For example, how many times is Not full! printed in the following example?

int full = 5; while(full < 5) { System.out.println("Not full!"); full++; }

The answer? Zero! On the first iteration of the loop, the condition is reached, and the loop exits. This is why while loops are often used in places where you expect zero or more executions of the loop. Simply put, the body of the loop may not execute at all or may execute many times.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх