The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


for Loops

The loops we have written so far have a number of elements in common. All of them start by initializing a variable; they have a test, or condition, that depends on that variable; and inside the loop they do something to that variable, like increment it.

This type of loop is so common that there is an alternate loop statement, called for, that expresses it more concisely. The general syntax looks like this:

    for (INITIALIZER; CONDITION; INCREMENTOR) {
      BODY
    }

This statement is exactly equivalent to

    INITIALIZER;
    while (CONDITION) {
      BODY
      INCREMENTOR
    }

except that it is more concise and, since it puts all the loop-related statements in one place, it is easier to read. For example:

    for (int i = 0; i < 4; i++) {
      System.out.println (count[i]);
    }

is equivalent to

    int i = 0;
    while (i < 4) {
      System.out.println (count[i]);
      i++;
    }

As an exercise, write a for loop to copy the elements of an array.



Last Update: 2011-01-24