Architecture & DesignHow to Use Different Types of Java Loops

How to Use Different Types of Java Loops

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The first stumbling block when we start learning any programming language is the concept of loops. Adding to the confusion, they are of various types. Loops are basically control statements. And, control statements provide the way to maneuver the flow of the program into different directions that are linear otherwise. A loop is a type of control statement which encircles the flow for a while—something like the vortexes in a river stream. This article describes the concept behind looping in Java and the various types of loops.

To take some additional classes on Java check out TechRepublic Academy!

Looping in Java

Java provides three repetition statements/looping statements that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These three looping statements are called for, while, and do…while statements. The for and while statements perform the repetition declared in their body zero or more times. If the loop continuation condition is false, it stops execution. The do…while loop is slightly different in the sense that it executes the statements within its body for one or more times.

There is a common structure of all types of loops, such as:

  • There is a control variable, called the loop counter.
  • The control variable must be initialized; in other words, it must have an initial value.
  • The increment/decrement of the control variable, which is modified each time the iteration of the loop occurs.
  • The loop condition that determines if the looping should continue or the program should break from it.

The variation in different types of loop structure is nothing but syntactic variations. We easily can replace one type of loop with another and still get the same result. The differences in them, I believe, are more of a choice when we look at the essence of it. But, when we look deeper, the subtle difference become pronounced, especially when we compare do…while with for and while loops. Let us take them, one by one, into account and investigate their working process.

The Java Loop: while

The while loop allows us to specify that a certain statement is to be executed repetitively until the loop condition is false. Consider a problem to print ten consecutive numbers from 1 to 10. What we do is initialize a control variable outside the while loop construct, state a condition for loop continuation, and then increment the control variable so that at some point of the iteration the condition become false and breaks out of the repetition.

Executing a while loop
Figure 1: Executing a while loop

int counter = 1;   // Control variable initialized

// Condition for loop continuation
while (counter <= 10) {
   System.out.println(counter);
   counter++;     // Increment the control variable
}

At first, the program control finds the variable named counter, initialized to 1. Then, on first encounter with the condition defined in the while loop, it evaluates to true because the value contained in the counter variable is 1, which is certainly less than ten. It than enters into the while body and executes the statement(s) inside the loop body, increments the counter to the next value and rebounds back to the while condition again. This time, the counter has value 2, which again is less than 10. The condition is evaluated to true; therefore, it enters into the while body, executes the statements, increments the counter to its next value, and so on. At some point in the iteration, the value of the counter will be 11, which is definitely greater than 10; the loop condition evaluates to false and breaks out.

The loop repetitively executes the System.out.println(…) statement as long as the condition statement counter<=10 evaluates to a Boolean true value. This means that if we write:

// Never-ending loop or infinite loop
while (true) {   // Condition is always true
   // ... Some statements
}

The loop condition has no reason to stop. Neither has the following code any reason to stop.

int counter = 1;   // Control variable initialized

// Condition always evaluates to true
while (counter <= 10) {
   System.out.println(counter);
   counter--;      // Decrements the control variable
}

These are typical examples of never-ending or infinite loops. It is a programmer’s responsibility to ensure that a loop eventually become false so that it stops; otherwise, the loop body will execute forever—or at least till the program is interrupted. Infinite loops are often common mistakes in a program.

Note: If such a situation occurs where a program executes infinitely, use a keyboard interrupt, such as Ctrl+C; this will terminate the running program.

Now, if we start the loop with a false condition:

// The loop body will never execute
while (false) {    // Condition is always false
   System.out.println("This will never print");
}

The statements inside the loop body will not get a chance to execute because the control will never enter the loop.

The Java Loop: for

The working process of a for loop is similar to the while loop, only the structure is different. Unlike the while loop, the layout of the control variable, loop condition, and the increment of the control statement can be stated in a single line of code, such as in the following example.

Executing a for loop
Figure 2: Executing a for loop

// For(<initialization>;<condition>;<increment>
for(int counter = 1; counter <= 10; counter++){
   System.out.println(counter);
}

Some variations in writing using a for loop are as follows:

int counter;
for( counter = 1; counter <= 10; counter++){
   //... Statements
}

int counter = 1;
for(; counter <= 10; counter++){
   //... Statements
}

int counter = 1;
for(; counter <= 10;){
   //... Statements
   counter++;
}

// Infinite loop
for(;true;);

Observe that, in some of the for loop structures, the initialization expression is declared outside the header and in some it is declared inside the for header. The difference is that if the control variable is declared inside the initialization section of the for loop, that variable is scoped within the for loop only. It will not exist outside it. However, when the control variable is declared outside for loop header it is scoped both inside and outside the for loop block.

Comparing Java Loops: for and while

Both the for and while loops are entry controlled; in other words, they first check the truth value of the condition and then only enter into the loop. There is certain point of dissimilarities in them, such as this:

// Infinite loop
for(;;);

This statement is completely valid and means an infinite loop, whereas

// Syntax error
while();

is a syntax error. Having said all this, there is no reason to favour or disfavour while for the for or for for the while in programming. Perhaps the problem of choice may be solved by choosing one. But, if one is really looking for a loop that does not check any sort of validity at its entry, the construct described next is for your consideration.

The Java Loop: do…while

This is an exit controlled looping structure which is different from, yet somewhat similar to, the while statement in the sense that the structure of the loop described, such as initialization of the control variable, is declared outside the loop header, the increment/decrement is written within the body of the loop like any other statements.

Executing a do...while loop
Figure 3: Executing a do…while loop

int counter = 1;   // Control variable initialized

do{
   System.out.println(counter);
   counter--;   // Decrements the control variable
}while(counter <= 10);   // Condition statement

The significant difference that sets the do…while loop apart from both while and for loop is that the for and while loops are meant to execute zero or more times. This means there is a chance that the loop may not execute at all if the condition is false. The do…while loop, on the other hand, executes at least once or, in other words, one or more times because it never checks any condition during its entry; rather, it evaluates the loop continuation condition statement only at the exit. This makes the body of the loop execute at least once.

Comparing Java Loops: while and do…while

It is not compulsory to use braces with the do…while loop statement if there is only one statement in the body. Similar is the case with the while loop. However, it is recommended to use braces with the do…while statement to avoid confusion with the while statement. For example,

while(counter++ <= 10);

or

while(counter <= 10)
   counter++;

This is a completely valid statement. The same can be written with a do…while loop.

do System.out.print("");
   while(counter++ <= 10);

or

do counter++; while(counter <= 10);

Now, observe the while part of both the while loop and do…while loop. They look the same. This may confuse the reader and cause them to misinterpret it. Therefore, it is recommended that the do…while statement be written with braces even if there is only one statement in the body.

do {
   counter++;
}while(counter <= 10);

This leverages the readability of the code and eliminates ambiguity between the while and do…while statements when they a contain single statement in the body.

Things to Avoid When Creating Java Loops

Java loops are great and serve many purposes within a program – they are part of nearly every software program out there. However, as helpful as loops are, they can also be dangerous. There are certain pitfalls when using loops that you want to be careful for, especially when programming with Java Loops.

One-Off Loop Errors in Java

One-off issues do not toss errors and, in fact, you may never even notice that there is a problem in your code at all. One-off problems in loops occur when a developer intends to have a loop execute a given number of times – let’s say 20 – but the loop actually only triggers 19 times. A common thing that causes this iteration problem in Java has to do with the use of <= or >= comparison operators. Programmers sometimes forget that these operators not only look for greater than or less than comparisons, but equal to as well. This flaw in logic is a simple one to mistake and can easily result in the on-off loop issue.

Infinite Loops in Java

The infamous infinite loop has been an issue in programming since the dawn of time. Infinite loops occur when a developer creates a loop routine that executes endlessly. While loops are infamous for this, as they state, while X, do X. Even something as simple as a misplaced semicolon added to the while statement can trigger an infinite loop.

Nested Loops in Java

We did not cover nested loops this go-round, as they are a more complicated topic. However, be aware that nested loops can be very tricky. They are not meant to be avoided, mind you. Rather, be aware that they need to be planned out carefully. Nested loops are loops that reside within other loops.

Conclusion

This concludes the story of loops, By the way, there is another variation of the for loop introduced in Java which is not covered here. The idea is that once the three basic types of loops are understood, the rest is a cakewalk. Things get a little messy when we go into nested loops, meaning one loop declared inside another. They make a hierarchy or tree structure when elaborated on a piece of paper. Maybe we’ll cover that concept later.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories