for, for-each and labels

A for loop puts the parts of a counted loop on one line: the starting state, the condition and the step. The enhanced form, for (T x : values), reads every element of an array or an Iterable without an index. Both can be nested, and a label names the loop that break or continue should act on.

The three-part for

The header has three parts separated by semicolons: an initialisation that runs once, a condition tested before every pass, and a step that runs after every pass. Any of them may be empty, and an empty condition means true, which is how an infinite loop is written when the body has its own exit.

The file ForLoop.java counts with two variables at once, one up and one down:

public class ForLoop { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 5; i++) { sum += i; } System.out.println("sum: " + sum); for (int i = 0, j = 10; i < j; i++, j--) { System.out.println(i + " " + j); } } }

javac -Xlint:all ForLoop.java
java ForLoop

sum: 15
0 10
1 9
2 8
3 7
4 6

The second loop declares two variables of the same type in the initialisation, moves both in the step and stops when they meet. The counter i is declared in the loop header, so it does not exist after the loop; that is one reason to prefer it to a counter declared before.

The enhanced for

for (String name : names) reads one element per pass and stops at the end of the array or collection. It has no index, so it cannot skip an element, read two neighbours or run backwards; for those, the three-part form is the right tool.

public class ForEach { public static void main(String[] args) { String[] names = {"Ada", "Grace", "Alan"}; for (String name : names) { System.out.println(name); } int[] numbers = {2, 4, 6}; int total = 0; for (int number : numbers) { total += number; } System.out.println("total: " + total); } }

javac -Xlint:all ForEach.java
java ForEach

Ada
Grace
Alan
total: 12

The loop variable is a copy of the element, so assigning to it inside the loop changes nothing in the array. An array of objects is different: the copy is a reference, and a method called on it changes the object both names point at.

Nested loops

A loop inside a loop runs the inner one completely for every pass of the outer one. break inside the inner loop ends only the inner loop; the outer one continues with its next pass, which is the cause of most nested-loop bugs.

public class Nested { public static void main(String[] args) { for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { if (col == 3) { break; } System.out.print(row * col + " "); } System.out.println(); } outer: for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { if (row * col > 4) { break outer; } System.out.println(row + " " + col); } } } }

javac -Xlint:all Nested.java
java Nested

1 2
2 4
3 6
1 1
1 2
1 3
2 1
2 2

Labelled break and continue

The first grid stops each row before its third column, so three rows of two products appear. The second loop has a label, outer:, before the outer for, and break outer leaves both loops at once: the pairs run to 2 2 and stop before 2 3, whose product is 6.

continue outer would end the current pass of the outer loop instead, and start its next pass. A label is a name, not a variable, and it must be followed by a loop with a colon; a label without a break or continue that names it does nothing.

Exercises

  1. Change the first loop in ForLoop.java to print the sum of the even numbers from 1 to 10.
  2. Use the enhanced for to find the largest number in an array of five values.
  3. Replace break outer in Nested.java with continue outer and predict the output before you run it.
  4. Write a nested loop that prints a 4 by 4 multiplication table, then one that prints only the lower triangle.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many parts does the header of a three-part for loop have?

    Answer

    Three, separated by semicolons

    Initialisation, condition and step; any of them may be empty.

  2. What can an enhanced for not do?

    Answer

    Read the index of the current element

    The enhanced form has no index, so skipping, reversing and reading neighbours need the three-part for.

  3. Which loop does a plain break end inside two nested loops?

    Answer

    The inner loop only

    break leaves the nearest enclosing loop; a label is needed to leave the outer one.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 4; i++) { sum += i; } System.out.println(sum); } }

    Answer

    10

    The loop adds 1, 2, 3 and 4, so the sum is 10.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int[] numbers = {2, 4, 6}; for (int number : numbers) { number = number * 2; } System.out.println(numbers[0]); } }

    Answer

    2

    The loop variable is a copy, so doubling it does not change the array element.

  6. What does this program print? public class Q3 { public static void main(String[] args) { for (int i = 0, j = 3; i < j; i++, j--) { System.out.println(i + " " + j); } } }

    Answer

    0 3 / 1 2

    The two counters meet after two passes: when i is 2 and j is 1 the condition is false.

  7. What does this program print? public class Q4 { public static void main(String[] args) { outer: for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 3; col++) { if (row * col > 2) { break outer; } System.out.println(row + " " + col); } } } }

    Answer

    1 1 / 1 2

    The product exceeds 2 at 1 3, and break outer leaves both loops there.

  8. What does this program print? public class Q5 { public static void main(String[] args) { int count = 0; for (int i = 0; i < 5; i++) { if (i % 2 == 0) { continue; } count++; } System.out.println(count); } }

    Answer

    2

    continue skips the even values, so only 1 and 3 are counted.

  9. What does an empty condition in for (int i = 0; ; i++) mean?

    Answer

    It is true, so only an exit in the body stops the loop

    A missing condition is treated as true, which is the usual way to write an endless loop.

  10. What does this program print? public class Q6 { public static void main(String[] args) { for (int row = 1; row <= 2; row++) { for (int col = 1; col <= 2; col++) { System.out.print(row + "" + col + " "); } } } }

    Answer

    11 12 21 22

    The inner loop prints two pairs per outer pass, all on one line because print adds no separator.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev