Step 2 of 7
for loops
Counting loops are so common that Java has a shorter way to write them. The for loop puts all three parts on one line, separated by semicolons:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
1
2
3
4
5for (start; condition; change) does the same as this while loop:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
- The start runs once, before the first round.
- The condition is checked before every round.
- The change runs at the end of every round.
A loop variable is often called i. Made in the for line, it only exists inside the loop. Counting down and other steps work too: for (int i = 10; i >= 1; i--) counts from 10 to 1, and i += 2 instead of i++ takes every second number.