OCP Oracle Certified Professional Java SE 17 Developer Study Guide. Jeanne Boyarsky
Читать онлайн книгу.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 (var counter = 4; counter>= 0; counter--) { System.out.print(counter + " "); }
Finally! We have code that now prints 4 3 2 1 0
and matches the reverse of our for
loop example in the previous section. We could have instead used counter > -1
as the loop termination condition in this example, although counter >= 0
tends to be more readable.
for
loops. When you see a for
loop on the exam, pay close attention to the loop variable and operations if the decrement operator, --
, is used. While incrementing from 0
in a for
loop is often straightforward, decrementing tends to be less intuitive. In fact, if you do see a for
loop with a decrement operator on the exam, you should assume they are trying to test your knowledge of loop operations.
Working with for Loops
Although most for
loops you are likely to encounter in your professional development experience will be well defined and similar to the previous examples, there are a number of variations and edge cases you could see on the exam. You should familiarize yourself with the following five examples; variations of these are likely to be seen on the exam.
Let's tackle some examples for illustrative purposes:
1 Creating an Infinite Loop for( ; ; ) System.out.println("Hello World");Although this for loop may look like it does not compile, it will in fact compile and run without issue. It is actually an infinite loop that will print the same statement repeatedly. This example reinforces the fact that the components of the for loop are each optional. Note that the semicolons separating the three sections are required, as for( ) without any semicolons will not compile.
2 Adding Multiple Terms to the for Statement int x = 0; for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) { System.out.print(y + " "); } System.out.print(x + " ");This code demonstrates three variations of the for loop you may not have seen. First, you can declare a variable, such as x in this example, before the loop begins and use it after it completes. Second, your initialization block, boolean expression, and update statements can include extra variables that may or may not reference each other. For example, z is defined in the initialization block and is never used. Finally, the update statement can modify multiple variables. This code will print the following when executed:0 1 2 3 4 5
3 Redeclaring a Variable in the Initialization Block int x = 0; for(int x = 4; x < 5; x++) // DOES NOT COMPILE System.out.print(x + " ");This example looks similar to the previous one, but it does not compile because of the initialization block. The difference is that x is repeated in the initialization block after already being declared before the loop, resulting in the compiler stopping because of a duplicate variable declaration. We can fix this loop by removing the declaration of x from the for loop as follows:int x = 0; for(x = 0; x < 5; x++) System.out.print(x + " ");Note that this variation will now compile because the initialization block simply assigns a value to x and does not declare it.
4 Using Incompatible Data Types in the Initialization Block int x = 0; for(long y = 0, int z = 4; x < 5; x++) // DOES NOT COMPILE System.out.print(y + " ");Like the third example, this code will not compile, although this time for a different reason. The variables in the initialization block must all be of the same type. In the multiple-terms example, y and z were both long, so the code compiled without issue; but in this example, they have different types, so the code will not compile.
5 Using Loop Variables Outside the Loop for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) System.out.print(y + " "); System.out.print(x); // DOES NOT COMPILEWe covered this already at the start of this section, but it is so important for passing the exam that we discuss it again here. If you notice, x is defined in the initialization block of the loop and then used after the loop terminates. Since x was only scoped for the loop, using it outside the loop will cause a compiler error.
Modifying Loop Variables
As a general rule, it is considered a poor coding practice to modify loop variables due to the unpredictability of the result, such as in the following examples:
for(int i=0; i<10; i++) i = 0; for(int j=1; j<10; j++) j++;
It also tends to make code difficult for other people to follow.
The for-each Loop
The for-each loop is a specialized structure designed to iterate over arrays and various Collections Framework classes, as presented in Figure 3.8.
FIGURE 3.8 The structure of an enhanced for-each loop
The for-each loop declaration is composed of an initialization section and an object to be iterated over. The right side of the for-each loop must be one of the following:
A built-in Java array
An object whose type implements java.lang.Iterable
We cover