Java: for loop

// Traditional, print 0 to 9
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
// Enhanced, iterate over collection
for (String s : listOfStrings) {
    System.out.println(s);
}

Traditional for loops

The following code runs instructions repeatedly until condition becomes false:

for (initialization; condition; step) {
    instructions
}
  • initialization runs before the first iteration
  • condition is evaluated before each iteration
    • If it evaluates to true, instructions are executed
  • step runs after each iteration
for (initialization; condition; step) { false true instructions }
Example: Add integers between 1 and 100
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("1 + 2 + ... + 100 = " + sum);
Example: Iterate over a linked list
for (Node n = list.head; n != null; n = n.next) {
    // process n
}

The scope of variables declared in the loop initialization (such as int i and Node n in the examples above) is limited to the loop.

Example:
for (int i = 0; i < 10; i++) {
    // ...
}
i = 123;  // Error: 'i' out of scope

Each component is optional.

Example: Omitting initialization and step components as follows…
for (; cond;) {
    ...
}
…is equivalent to while (cond) { ... }

If condition is left empty it defaults to true.

Example: Infinite loop
for (;;) {
    System.out.println("Looping forever!");
}

For each loop (“Enhanced for loop”)

The following code iterates over the elements in iterable:

for (Type elem : iterable) {
    // process elem
}

Where iterable can be

  • An array, such as a String[], or
  • An implementation of Iterable such as an ArrayList or a HashSet.

Behind the scenes

In case iterable is an array, the above snippet is equivalent to

for (int i = 0; i < iterable.length; i++) {
    Type elem = iterable[i];
    // process elem
}

In case iterable is an Iterable, it’s equivalent to

Iterator<Type> iter = iterable.iterator();
while (iter.hasNext()) {
    Type elem = iter.next();
    // process elem
}

Auto boxing

Thanks to auto (un)boxing, you can for instance use an int to iterate over a list of Integer:

Example:
List<Integer> ints = new ArrayList<>();
// ...
for (int i : ints) {
    // ...
}

Optional Braces

For single statement bodies, the braces are optional, just as with if and while statements.

Example: These two snippets are equivalent:
for (int i : arr) {
    System.out.println(i);
}
System.out.println("done");
for (int i : arr)
    System.out.println(i);

System.out.println("done");

The official style guide does however madate the use of braces for safety.

Accidental semicolon

There should not be a semicolon after the loop declaration: for (…); { … }. See Beware of accidental semicolons in while and for loops!

Comments

Be the first to comment!