Java for loop
›Short versionOpen if you only have a minute.
- for (init; condition; update) runs init once, then tests, runs the body, and updates, in that order.
- The update runs after the body, and it still runs when the body uses continue.
- i < 5 from 0 visits 0 through 4. i <= 5 also visits 5.
- An array index stops at length - 1. The matching test is i < array.length.
- for-each walks each element. Assigning to the loop variable does not replace the array slot.
A loop is the counted loop. The header holds the , the , and the , so the thing that makes the loop end is visible before the body. A while loop hides that step inside the block, which is why a missed increment is easier to write there.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}What the console shows
0 1 2 3 4
i is created once, at 0. The condition is checked, the body prints, then i++ runs, then the condition is checked again. When i is 5 the condition fails and the body does not print 5. The is the last allowed value, and < versus <= is how you choose it.
One step past the last legal index
Counting to a limit and indexing an array use the same header, and they do not want the same comparison. An array of length 5 has indexes 0, 1, 2, 3, and 4.
String[] cars = {"Volvo", "BMW", "Ford", "Mazda", "Fiat"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}The update can step by more than one: for (int i = 0; i < 10; i += 2) prints the even numbers from 0 through 8. A nested loop uses a second name, usually j, and the inner loop runs all of its passes for each single pass of the outer one. break and continue affect the loop they sit in, which is the next page.
Walking elements when you do not need the index
A loop is the form that cannot get the bound wrong, because there is no index. Use it to read every element. Use the counted loop when you need the position, or when you need to write a new value into a slot.
String[] cars = {"Volvo", "BMW", "Ford"};
for (String car : cars) {
System.out.println(car);
}
int[] nums = {1, 2, 3};
for (int n : nums) {
n = n * 2;
}
System.out.println(nums[0]);The names print in order. The last print is 1. n = n * 2 changes the copy the loop handed you. The array slot is untouched. Replacing nums[i] requires the counted loop and the index i.
When the number of passes is not a count you can write in the header, the while loop is the clearer statement. The slots these loops walk are arrays.
A loop is written for (int i = 0; i <= cars.length; i++) on an array of five names. What happens on the last pass?
i runs 0, 1, 2, 3, 4, and then 5, because <= still allows a value equal to the length. cars[5] is past the last element. That pass throws ArrayIndexOutOfBoundsException. i < cars.length stops after index 4.