Summary
In this chapter, we discussed how Java implements iteration (looping). We started with the while
loop, which, because the condition is at the start of the loop, will execute zero or more times. In contrast, the do-while
loop, where the condition is at the end of the loop, will execute one or more times. The while
and do-while
loops are very useful when you do not know how many times a loop will iterate.
In contrast, the traditional for
loop is extremely useful when you do know how often you want a loop executed. The traditional for
loop’s header consists of three parts: the initialization section, the boolean expression, and the increment/decrement section. Thus, we can iterate a discrete number of times. This makes the traditional for
loop ideal for processing arrays.
The enhanced for
(for-each
) loop is even more suitable for processing arrays (and collections), provided you are not interested in the current loop iteration index. Being concise, succinct, and easy...