Java Reference
In-Depth Information
35
42
49
56
63
70
77
84
91
98
The third for loop demonstrates using the comma operator to perform mul-
tiple statements in the update step. The for loop is declared as:
for(int a = 1, b = 100; a < b; a = a + 2, b = b - 4)
Two variables, a and b, are declared and initialized in the initialization step.
In the update step, I wanted to add 2 to a and subtract 4 from b. You can have
more than one statement in the update step by separating the statements with
a comma. This loop executes 17 times, which is how many times it takes for a
to become larger than b, and generates the following output:
a = 1 and b = 100
a = 3 and b = 96
a = 5 and b = 92
a = 7 and b = 88
a = 9 and b = 84
a = 11 and b = 80
a = 13 and b = 76
a = 15 and b = 72
a = 17 and b = 68
a = 19 and b = 64
a = 21 and b = 60
a = 23 and b = 56
a = 25 and b = 52
a = 27 and b = 48
a = 29 and b = 44
a = 31 and b = 40
a = 33 and b = 36
The break Keyword
The
break
keyword can be used in any of the loop control structures to cause
the loop to terminate immediately. When a break occurs, no matter what the
value is of the loop counter or the Boolean expression, the flow of control will
jump to the next statement past the loop.