2.2 Loop StatementsHomepage  « Java5 Certification « 2.2 Loop Statements

In this lesson we investigate the different types of loops available in java and the iterators and their usage within a loop. We will also look at how we can break from a loop, continue from within a loop and label a loop to continue execution from.

Lets take a look at the points outlined at the Oracle Website for this part of the certification.

  • Section 2: Flow Control

    • Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

The for Statementgo to top of page Top

The for statement will loop through a section of code a set number of times. The for statement is very versatile and has two different variations known commonly as the for loop and the enchanced for loop.

The for loop contains three parts. In the first part we initialize a counter variable with a value, this only happens on initial entry to the for loop. The second part is a condition which tests the variable value at the start of each loop and if the condition is no longer true the for loop is exited. The final part of the for statement is an expression to be evaluated at the end of each iteration of the loop. This normally takes the form of a counter that is decremented or incremented.

The enchanced for loop was introduced in Java5 and implements a for-each style loop that iterates through a collection of objects in a sequential order from start to finish.

The following table shows the different forms of the for construct that can be used. We are using blocks of code to wrap statements which is optional when using a single statement, but good practice and will be used here.

Construct Description
for loop
for ([initialization]; [condition]; [iteration]) {
    statement body;
}
The initialization, condition, iteration and statement body components of a for statement are all optional.

The following will create an infinite for loop :
for (;;) {...} // Infinite loop.

The following will create a for loop with no body:
for (int i=1; i<5; i++); // No body

The initialization component is generally an assignment statement that sets the initial value of a control variable used to control iteration of the loop.

The condition component is a conditional expression that is always tested againt the control variable for true before each iteration of the loop. So if this is false to begin with then any statement body component will never be executed.

The iteration component is an expression that determines the amount the control variable is changed for each loop iteration.

The statement body is executed each time the condition component returns true when tested againt the control variable.
enhanced for loop
for (declaration : expression) {
    statement body
}
The declaration component declares a variable of a type compatible with the collection to be accessed which will hold a value the same as the current element within the collection.

The expression component can be the result of a method call or an expression that evalutes to a collection type.

The statement body is executed each time an element of the collection is iterated over.

Example usage of the different forms of the for statement is shown in the Beginning Java5 - Loop Statements lesson.

The while Statementgo to top of page Top

The while statement can be used to loop through a section of code while a condition remains true. The while statement has two different variations known commonly as the while loop and the do-while loop.

The following table shows the different forms of the while construct that can be used. We are using blocks of code to wrap statements which is optional when using a single statement, but good practice and will be used here.

Construct Description
while loop
while (condition) {
    statement body;
}
The condition can be any expression that results in a boolean and the loop will continue while the expression remains true, processing the statement body on each pass.

When the condition returns false the loop ends and control is passed to the next line following the loop.

Therefore if the condition starts as false the loop will never be entered.
do while loop
do {
    statement body;
} while (condition);
Unlike the normal while loop the statement body is processed before the condition is tested. The condition can be any expression that results in a boolean and the loop will continue while the expression remains true.

When the condition returns false the loop ends and control is passed to the next line following the loop.

Therefore even if the condition starts as false the loop will always execute at least once.

while Rules and Examples

There are a few rules to remember when coding the while and do while statements:

  • The expression we check against, in the parentheses, must evaluate to a boolean type: true or false.
  • When coding the while statement remember that the loop will never be executed if the expression we check against, in the parentheses resolves to false on loop entry.
  • When coding the do while statement remember that the loop will always be executed at least once, regardless of whether the expression we check against, in the parentheses resolves to false on loop entry.

Following are some examples showing while and do while statement usage:


/*
  Some code showing while and do while statement usage
*/
boolean b = true;
int i = 2;

 // while
while (b) {
    System.out.println("This is executed");
    break;
}   

while (i == 2) {
    System.out.println("This is executed");
    break;
}   

while (i) { // Will not compile, does not evaluate to boolean
    System.out.println(" ");
}   

while (i = 2) { // Assignment not evaluation, so won't compile
    System.out.println(" "); 
}   

while (true) { // This is fine
    System.out.println("This is executed");
    break;
} 

while (true) { // This is fine but loops endlessly
    System.out.println("This is executed");
} 
  
// do while
do {
    System.out.println("This is executed once"); 
} while (false);

do {
    System.out.println("This is executed once"); 
    b = false;
} while (b);

Example usage of the different forms of the while statement is shown in the Beginning Java5 - Loop Statements lesson.

Related Java5 Tutorials

Beginning Java5 - Loop Statements

<<  2.1 If & Switch Statements                    2.3 Using Assertions  >>

go to home page Java5 Tutor Homepage go to home page Top