Looping Construct: for Loop

The for statement, popularly called for loop is the most often used looping construct in Java. A for loop is used to iterate over a range of values.

Structure of for Loop

The general structure of for statement is as follows –

1234567for (initializationExpression,terminationExpression,modificationExpression) { // code block of the loop }

As seen above, the constituents of a for statement are –
1. initializationExpression – this expression is evaluated exactly once. It typically initializes any variable that controls the execution of the loop.
2. terminationExpression – the loop is executed as long as this expression evaluates to true. This expression is evaluated at the beginning of each iteration.
3. modificationExpression – this expression is evaluated at the end of each iteration. This expression typically modifies the value of variable that controls execution of loop.
4. Loop’s code block – the set of statements that are executed in an iteration.

All three expressions of the for loop are optional. You can omit one or more of these expressions without causing syntax errors. For example, the code below demonstrates an infinite loop – again using our favorite example of class Politician.Infinite loopJava

12345678910public class Politician {   public void rob() {    // an infinite loop    // no initialization, modification or termination conditions    for ( ; ; ) {      depositInSwissAcounts();    } // end of for loop’s code block  }}

Enhanced for Loop

  1. The enhanced for loop was introduced in Java 5.
  2. This is used for iterating over Arrays and Collections. Any class that implements Iterable can be used in an enhanced for loop.
  3. This is a readonly loop. You can not modify the  variable that has been read.
  4. Wherever possible prefer enhanced for loop over traditional for loop

The enhanced for loop is a convenience feature to read (and only read) elements of an array or a collection. The general form of the enanced for loop is –

123456789for ( Type anElement : collectionOfElements) { // anElement is available for reading // can use anElement to change contents of object referenced to // but the collection itself cannot be changed }

And here is a small demo of our Politician reading all his bank accounts –Java

1234567891011121314151617// an array of all bank accounts of a politicianBankAccount[] politiciansAccounts; // assume the Interpol has filled the above array for us for (BankAccount anAccount : politiciansAccounts) {  // one by one all accounts appear as anAccount  // each iteration has different account in anAccount   // can read anAccount  // can change the properties of object referenced by anAccount  // even assign null to it  // but cannot make anAccount disappear from the array   // do something about the account}….

Leave a comment

Your email address will not be published.