Java Reference
In-Depth Information
which would produce the following output:
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
But this approach is tedious. The program has five statements that are very similar.
They are all of the form:
System.out.println(number + " squared = " + (number * number));
where number is either 1 , 2 , 3 , 4 , or 5 . The for loop avoids such redundancy. Here is
an equivalent program using a for loop:
1 public class WriteSquares2 {
2 public static void main(String[] args) {
3 for ( int i = 1; i <= 5; i++) {
4 System.out.println(i + " squared = " + (i * i));
5 }
6 }
7 }
This program initializes a variable called i to the value 1 . Then it repeatedly
executes the println statement as long as the variable i is less than or equal to 5 .
After each println , it evaluates the expression i++ to increment i .
The general syntax of the for loop is as follows:
for (<initialization>; <continuation test>; <update>) {
<statement>;
<statement>;
...
<statement>;
}
You always include the keyword for and the parentheses. Inside the parentheses
are three different parts, separated by semicolons: the initialization, the continuation
test, and the update. Then there is a set of curly braces that encloses a set of state-
ments. The for loop controls the statements inside the curly braces. We refer to the
controlled statements as the body of the loop. The idea is that we execute the body
multiple times, as determined by the combination of the other three parts.
The diagram in Figure 2.1 indicates the steps that Java follows to execute a for
loop. It performs whatever initialization you have requested once before the loop
begins executing. Then it repeatedly performs the continuation test you have provided.
 
Search WWH ::




Custom Search