Java Keywords (Part VII): Loops
This article will cover the keywords used for looping: for
, do
, and while
, as well as the keywords used to change the flow of loops: break
and continue
.
Java keyword list
abstract | continue | for | new | switch |
assert | default | goto* | package | synchronized |
boolean | do | if | private | this |
break | double | implements | protected | throw |
byte | else | import | public | throws |
case | enum | instanceof | return | transient |
catch | extends | int | short | try |
char | final | interface | static | void |
class | finally | long | strictfp | volatile |
const* | float | native | super | while |
Although the list above is arranged in alphabetical order, I will go through them in a different order.
Loop Operations
In my years teaching Java programming in college, I don't recall a topic that that got students more exciting than Loops. This is because up to that point, basic programs were not as exciting. You can only do "Hello World!" so many times before it becomes boring. But I wasn't surprised because this topic had the same effect when I was a student. Loops allow you to simplify your code by enclosing within them units of code that you wish to repeat for a determinate period (or number) of times. As mentioned in the introduction, there are three loop structures in Java: thefor
loop, the while
loop, and the do/while
loop.
The main purpose of loop structures is to simplify code. Suppose a block of code is to be executed 100 times. It makes little sense to copy an paste the same code 100 times sequentially. Suppose you want to write code that will read you a line of text as long as there are lines to read in a book. Since you may not know how many lines of text a particular book may have, it will be nearly impossible to copy and paste this read operation. Also, two books may not have the same number of lines. Therefore, the number of iterations will vary depending of which book you wish to read. Those scenarios are basically impossible to code without loop operations.
Classic for loop
The basic structure of the classicfor
loop is as follows:
for (initialization condition; loop termination condition; loop count update) {
// Execute whatever is inside this block the loop
// until the termination condition is met
}
- The initialization condition initializes the loop. It executes once, when the first iteration of the loop starts.
- When the termination condition evaluates to false, the loop terminates and the rest of the program resumes.
- The loop count variable is updated after at the end of each iteration. This expression can increment or decrement the counter loop value.
- Typically, the loop is executed the number of times determined by the loop termination condition.
You could also write a loop that
while loop
A while loop is a structure similar to the for-loop. However, the looping condition is evaluated prior entering the loop. Because of that, the code inside the loop will be executed zero or more times. In order to enter the loop, the Boolean expressions that determines the looping condition must evaluate to true. Assuming that the looping condition is met, the code inside the loop will be executed. The looping condition reevaluated at the beginning of each iteration. The caveat of this type of loop is that the programmer must add code to force a change the value of this Boolean expression to false. Otherwise, the loop will run endlessly. For now, assume that endless looping is an undesirable condition. The general form of a while loop is as follows:
while (looping condition is true) {
// Execute whatever is inside this block the loop
// until the looping condition is no longer true
}
do-while loop
A do-while loop is a structure similar to the while loop, except that the code inside the loop will be executed at least once and the looping condition is evaluated at the end of each loop. As the case with the while-loop, the caveat of this type of loop is that the programmer must add code to force a change the value of this Boolean expression to false. Otherwise, the loop will run endlessly. For now, assume that endless looping is an undesirable condition. The general form of a while loop is as follows:
do {
// Execute whatever is inside this block the loop
// until the looping condition is no longer true
} while (looping condition is true); // Not ending with semi-colon is a syntax error
Next up, Part VIII: Skipping Loop Iterations and Escaping Loops
This comment has been removed by the author.
ReplyDeleteI find loops most useful for traversing arrays, vectors and other data structures used to contain a sequence of elements. Regarding Java, it is useful to quickly traverse an array of elements with 2 or 3 lines of code - using a for loop from 0 -> array.length. Performing array operations inside of a for loop make it so you don't exceed the array bounds and leak memory or crash the program.
ReplyDeleteAlthough nested-loops can get overwhelming very quickly so it is best to make comments to label the purpose of the loop.
Now with Lambda Expressions, you can do even more powerful traversing; especially when your data structures are large. At some point (hopefully soon) I will write about Lambda Expressions. If you haven't explore them, I suggest you do and also stay tuned.
DeleteLoop is found particularly strong in programming. We have many ways to customize loop. For example, we can use the break statement to stop a for loop, use the continue statement to stop a single for lop but keep doing the remaining loops. Moreover, manipulations with array is strongly associative with loops.
ReplyDeleteLoops are a huge part of coding, it is the sort of the back bone of programming. Even though there are number of loops like do, while , and do-while they fundamentally the same. One just loop as it is, one loops with exceptions and etc. Array manipulation is done with loops also.
ReplyDelete