Название: OCP Oracle Certified Professional Java SE 17 Developer Study Guide
Автор: Jeanne Boyarsky
Издательство: John Wiley & Sons Limited
Жанр: Программы
isbn: 9781119864592
isbn:
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 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.
Why i in for Loops?
You may notice it is common practice to name a for
loop variable i
. Long before Java existed, programmers started using i
as short for increment variable, and the practice exists today, even though many of those programming languages no longer do! For double or triple loops, where i
is already used, the next letters in the alphabet, j
and k
, are often used.
Printing Elements in Reverse
Let's say you wanted to print the same first five numbers from zero as we did in the previous section, but this time in reverse order. The goal then is to print 4 3 2 1 0
.
How would you do that? An initial implementation might look like the following:
for (var counter = 5; counter> 0; counter--) { System.out.print(counter + " "); }
While this snippet does output five distinct values, and it resembles our first for
loop example, it does not output the same five values. Instead, this is the output:
5 4 3 2 1
Wait, that's not what we wanted! We wanted 4 3 2 1 0
. It starts with 5
, because that is the first value assigned to it. Let's fix that by starting with 4
instead:
for (var counter = 4; counter> 0; counter--) { System.out.print(counter + " "); }
What does this print now? It prints the following:
4 3 2 1
So close! The problem is that it ends with 1
, not 0
, because we told it to exit as soon as the value was not strictly greater than 0
. If we want to print the same 0
through 4
as our first example, we need to update the termination condition, like this:
for СКАЧАТЬ