ТОП просматриваемых книг сайта:
OCP Oracle Certified Professional Java SE 17 Developer Study Guide. Jeanne Boyarsky
Читать онлайн.Название OCP Oracle Certified Professional Java SE 17 Developer Study Guide
Год выпуска 0
isbn 9781119864592
Автор произведения Jeanne Boyarsky
Жанр Программы
Издательство John Wiley & Sons Limited
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.
The do/while Statement
The second form a while
loop can take is called a do/while loop, which, like a while
loop, is a repetition control structure with a termination condition and statement, or a block of statements, as shown in Figure 3.6.
FIGURE 3.6 The structure of a do
/while
statement
Unlike a while
loop, though, a do
/while
loop guarantees that the statement or block will be executed at least once. For example, what is the output of the following statements?
int lizard = 0; do { lizard++; } while(false); System.out.println(lizard); // 1
Java will execute the statement block first and then check the loop condition. Even though the loop exits right away, the statement block is still executed once, and the program prints 1
.
Infinite Loops
The single most important thing you should be aware of when you are using any repetition control structures is to make sure they always terminate! Failure to terminate a loop can lead to numerous problems in practice, including overflow exceptions, memory leaks, slow performance, and even bad data. Let's take a look at an example:
int pen = 2; int pigs = 5; while(pen < 10) pigs++;
You may notice one glaring problem with this statement: it will never end. The variable pen
is never modified, so the expression (pen < 10)
will always evaluate to true
. The result is that the loop will never end, creating what is commonly referred to as an infinite loop. An infinite loop is a loop whose termination condition is never reached during runtime.
Anytime you write a loop, you should examine it to determine whether the termination condition is always eventually met under some condition. For example, a loop in which no variables are changing between two executions suggests that the termination condition may not be met. The loop variables should always be moving in a particular direction.
In other words, make sure the loop condition, or the variables the condition is dependent on, are changing between executions. Then, ensure that the termination condition will be eventually reached in all circumstances. As you learn in the last section of this chapter, a loop may also exit under other conditions, such as a break
statement.
Constructing for Loops
Even though while
and do
/while
statements are quite powerful, some tasks are so common in writing software that special types of loops were created—for example, iterating over a statement exactly 10 times or iterating over a list of names. You could easily accomplish these tasks with various while
loops that you've seen so far, but they usually require a lot of boilerplate code. Wouldn't it be great if there was a looping structure that could do the same thing in a single line of code?
With that, we present the most convenient repetition control structure, for
loops. There are two types of for
loops, although both use the same for
keyword. The first is referred to as the basic for
loop, and the second is often called the enhanced for
loop. For clarity, we refer to them as the for
loop and the for-each loop, respectively, throughout the book.
The for Loop
A basic for loop has the same conditional boolean
expression and statement, or block of statements, as the while
loops, as well as two new sections: an initialization block and an update statement. Figure 3.7 shows how these components are laid out.
Although Figure 3.7 might seem a little confusing and almost arbitrary at first, the organization of the components and flow allow us to create extremely powerful statements in a single line that otherwise would take multiple lines with a while
loop. Each of the three sections is separated by a semicolon. In addition, the initialization and update sections may contain multiple statements, separated by commas.
Variables declared in the initialization block of a for
loop have limited scope and are accessible only within the for
loop. Be wary of any exam questions in which a variable is declared within the initialization block of a for
loop and then read outside the loop. For example, this code does not compile because the loop variable i
is referenced outside the loop:
FIGURE 3.7 The structure of a basic for
loop
for(int i=0; i < 10; i++) System.out.println("Value is: "+i); System.out.println(i); // DOES NOT COMPILE
Alternatively, variables declared before the for
loop and assigned a value in the initialization block may be used outside the for
loop because their scope precedes the creation of the for
loop.
int i; for(i=0; i < 10; i++) System.out.println("Value is: "+i); System.out.println(i);
Let's take a look at an example that prints the first five numbers, starting with zero:
for(int i = 0; i < 5; i++) { System.out.print(i + " "); }
The local variable i
is initialized first to 0
. The variable i
is only in scope for the duration of the loop and is not available outside the loop once the loop has completed. Like a while
loop, the boolean
condition is evaluated on every iteration of the loop before the loop executes. Since it returns true
, the loop executes and outputs 0
followed by a space. Next, the loop executes the update section, which in this case increases the value of i
to 1
. The loop then evaluates the boolean
expression a second time, and the process repeats multiple times, printing the following:
0 1 2 3 4
On