Java Keywords (Part VII): Loops


The Java keyword list has 21 keywords grayed out. That puts us at 42% of keywords covered by these series of articles. Amazingly, that's almost enough knowledge to built simple applications. I suggest that if you have not read any of the articles in Java Keyword series, go back read them before proceeding further. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page.

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
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

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: the for 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 classic for 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
}
When using the classic version of this loop:
  1. The initialization condition initializes the loop. It executes once, when the first iteration of the loop starts.
  2. When the termination condition evaluates to false, the loop terminates and the rest of the program resumes.
  3. The loop count variable is updated after at the end of each iteration. This expression can increment or decrement the counter loop value.
  4. Typically, the loop is executed the number of times determined by the loop termination condition.
It is imperative that the termination condition takes in consideration how the loop counter variable is modified to break when the count reaches a certain value. Otherwise, an infinite loop condition could occur. For example, if we desire to loop 10 times, if we start the loop with a counter loop variable of 1, our break condition (to stop after the tenth iteration) must be counter variable > 10 or counter variable >= 11.

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
}
There is no performance advantage of the while-loop over the for-loop or vice versa. Therefore, it is (mostly) a matter of preference which of the two to use in any given case.

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
There is no performance advantage of the do-while loop over the for-loop or vice versa. Therefore, it is (mostly) a matter of preference which of the two to use in any given case. But, there are times where it makes more sense to use a do-while over a while. However, since it is a matter of preference based on performance, most developers use the while loop over the do-while, making sure that the looping condition to be met so that the while loop is executed at least once. In my opinion, this is not necessary since there is already a looping structure that allows for a loop to be executed 1-or-many times. So, why not use it?

Next up, Part VIII: Skipping Loop Iterations and Escaping Loops

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I 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.

    Although nested-loops can get overwhelming very quickly so it is best to make comments to label the purpose of the loop.

    ReplyDelete
    Replies
    1. 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.

      Delete
  3. Loop 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.

    ReplyDelete
  4. Loops 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

Post a Comment

Popular posts from this blog

Implementing Interfaces with Java Records

Customizing Java Records

Exception Handling: File CRUD Operations Example