Java Reference
In-Depth Information
for(int j = 1; j <= 1024; j = j * 2)
{
System.out.println(j);
}
The first step that occurs is j being initialized to 1; j then is tested to see if it
is less than or equal to 1024, which is true, so the body of the for loop executes
and 1 is displayed. The flow of control then jumps up to the update statement
j = j * 2, and j becomes 2. Because 2 is less than or equal to 1024, the loop repeats
again and 2 is displayed.
This process repeats, and j becomes 4, 8, 16, and so on until it equals 2048, at
which point the loop terminates. The output will look similar to:
1
2
4
8
16
32
64
128
256
512
1024
This could have been done using a while loop similar to the following:
int j = 1;
while(j <= 1024)
{
System.out.println(j);
j = j * 2;
}
The end result is the same, so I do not want to imply that one technique is
better than the other. For loops are widely used, though, and are an
important fundamental piece of Java.
As with while loops and do/while loops, it is possible to write a for loop
that never executes, which happens when the Boolean expression is
initially false. Similarly, you can write an infinite for loop that never
terminates, which happens when the Boolean expression never becomes
false.
Search WWH ::




Custom Search