You have already seen a couple of examples of iteration and looping in Java. So this section will just serve as a reference for the differences in syntax.
A definite loop, also known as a for loop, is a loop that is executed for a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop structure in conjunction with the range function. Listing 5.1.3 shows the syntax for the range function.
The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. Listing 5.1.4 shows how the Java for loop is written.
In Python, the for loop can also iterate over any sequence such as a list, a string, or a tuple. Java also provides a variation of its for loop that provides the same functionality in its so-called for each loop.
Listing 5.1.8 stretches the imagination a bit, and in fact points out one area where Java’s primitive arrays are easier to use than an array list. Listing 5.1.9 shows how the for loop can be used to iterate over all elements in a primitive array in Java.
Rearrange the blocks to create a Java method that accepts an upper bound integer limit and calculates the sum of all even numbers from 2 up to and including limit.
public int sumEvens(int limit) {
---
int total = 0;
---
int total;
#paired
---
for (int i = 2; i <= limit; i += 2) {
---
for (int i = 2; i < limit; i =+ 2) {
#paired
---
total += i;
}
---
total = i;
}
#paired
---
return total;
}
---
return i;
}
#paired