The for loop
In the last lesson's while loop, the lap number lived in three different places. The variable was declared before the loop, checked in the condition and changed at the end of the body. Get one of the three wrong, and the loop either never starts or never ends.
The runner has the same three jobs. Before the start, they set the board to 1 once. Before each lap, they look at the board. After each lap, they add one to the number.
The for loop gathers all three jobs into one line. Here is a program that adds up the numbers from 1 to 100:
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum); // 5050
}
}Let's go through it line by line:
int sum = 0;sets up the sum.for (int i = 1; i <= 100; i++)repeats the body forifrom1to100.sum += i;adds the currentito the sum. For anintit does the same assum = sum + i, only shorter.System.out.println(sum)runs after the loop and prints5050.
The three parts of the header
The line for (int i = 1; i <= 100; i++) is called the loop header. Its parentheses hold three parts separated by semicolons:
int i = 1is the initialization: it runs once, before the first iteration. The runner sets the board to1.i <= 100is the condition: it is checked before every iteration, as inwhile. The runner looks at the board.i++is the update: it runs after the body, before the next check. The runner adds one to the number.
The header reads left to right, but it runs in a different order:
- The initialization, once.
- The condition. If it is false, the loop ends.
- The body.
- The update, and back to item 2.
The update is written in the header before the body, but it runs after it. Interviewers like to ask about exactly this order. The widget shows the same loop, only up to 3: press "Next step" and watch which part of the header runs right now.
1public class Main {2 public static void main(String[] args) {3 int sum = 0;4 for (int i = 1; i <= 3; i++) {5 sum += i;6 }7 System.out.println(sum);8 }9}
int sum = 0 sets up the sum.
By the time the widget reaches println, the variable i no longer exists. It was declared right in the header, and it lives only inside the loop.
This is where the stadium picture parts ways with Java. The board at the stadium stays there after the race, but the variable from a for header does not exist after the loop.
Other header forms
The update does not have to add one. -- subtracts one, and += adds any number:
for (int i = 0; i < 5; i++): five iterations,ifrom0to4;for (int i = 3; i >= 1; i--): a countdown,3,2,1;for (int i = 0; i <= 10; i += 2): the even numbers from0to10.
i++ and ++i
The ++ operator adds one to a variable. It is called the increment, and it has two forms. As a statement on its own, as in the loop update, they work the same. The difference shows when the value of ++ goes on somewhere: into printing, into an assignment, into another expression.
int n = 3;
System.out.println(n++); // 3
System.out.println(n); // 4
System.out.println(++n); // 5
System.out.println(n); // 5The postfix form n++
++ stands after the name. The expression n++ gives the old value of the variable and adds one only afterwards. That is why the first line prints 3, although after it n equals 4: the second line shows that.
The prefix form ++n
++ stands before the name. The expression ++n adds one first and then gives the new value. The third line raises n from 4 to 5 and prints 5.
The order of writing helps you remember: whatever comes first happens first. In n++ the name comes first, so the value is taken first. In ++n the ++ comes first, so one is added first. -- works the same way: n-- gives the old value, --n the new one.
Interviewers often check this difference: they show a short program with i++ and ++i and ask what it prints. In your own code, to stay out of trouble, write ++ as a statement on its own, not inside another expression.
Common mistake
The value of i is needed after the loop:
for (int i = 1; i <= 3; i++) {
System.out.print(i + " ");
}
System.out.println(i); // ✗error: cannot find symbolThe compiler does not know the name i on the last line: the variable from the header is gone together with the loop. The message is the same as for a variable you forgot to declare. If you need a value after the loop, keep it in a variable declared before the loop, like sum in the first example.
Key points
- The
forinitialization runs once, the condition before each iteration, the update after the body. n++gives the old value and then adds one, while++nadds one and gives the new value.- As statements on their own,
i++and++iwork the same. - A variable declared in a
forheader exists only inside the loop.