Java Reference
In-Depth Information
Infinite loop II
for( ; true; ); // Explicit true is used here
A break statement is used to stop the execution of a for -loop statement. When a break statement is executed,
the control is transferred to the next statement, if any, after the for -loop statement. You can rewrite the for -loop
statement to print all integers between 1 and 10 using a break statement.
for(int num = 1; ; num++) { // No condition-expression
System.out.println(num); // Print the number
if (num == 10) {
break; // Break out of loop when i is 10
}
}
This for -loop statement prints the same integers as the previous for -loop statement did. However, the latter is
not recommended because you are using a break statement instead of using the condition-expression to break out of
the loop. It is good programming practice to use a condition-expression to break out of a for loop.
Expression-list
The expression-list part is optional. It may contain one or more expressions separated by a comma. You can use only
expressions that can be converted to a statement by appending a semicolon at the end. Please refer to the discussion
on the expression statement in the beginning of this chapter for more details. You can rewrite the same example of
printing all integers between 1 and 10 as follows:
for(int num = 1; num <= 10; System.out.println(num), num++);
Note that this for -loop statement uses two expressions in the expression-list, which are separated by a comma.
A for -loop statement gives you more power to write compact code.
You can rewrite the above for -loop statement as follows to make it more compact and accomplish the same task:
for(int num = 1; num <= 10; System.out.println(num++));
Note that you combined the two expressions in the expression-list into one. You used num++ as the argument
to the println() method, so it prints the value of num first, and then increments its value by 1. Can you predict the
output of the above for -loop statement if you replace num++ by ++num ?
You can also use nested for -loop statements, that is, for -loop statements inside another for -loop statement.
Suppose you want to print a 3x3 (read as three by three) matrix.
11 12 13
21 22 23
31 32 33
 
Search WWH ::




Custom Search