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

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 the fifth iteration of the loop, the value of i reaches 4 and is incremented by 1 to reach 5. On the sixth iteration of the loop, the boolean expression is evaluated, and since (5 < 5) returns false, the loop terminates without executing the statement loop body.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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