Java Reference
In-Depth Information
// Using a switch statement
switch (i) {
case 10:
System.out.println(“i is 10");
break;
case 20:
System.out.println("i is 20");
break;
default:
System.out.println("i is neither 10 nor 20");
}
The for Statement
A
for
statement is an iteration statement (also called a
for
-loop statement), which is used to loop through a
statement for a number of times based on some conditions. The general form of a
for
-loop statement is
for (initialization; condition-expression; expression-list)
Statement
The initialization, condition-expression, and expression-list are separated by a semicolon. A
for
-loop statement
consists of four parts:
•
Initialization
•
Condition-expression
•
Statement
•
Expression-list
First, the initialization part is executed; then, the condition-expression is evaluated. If the condition-expression
evaluates to
true
, the statement associated with the
for
-loop statement is executed. After that, all expressions in
the expression-list are evaluated. The condition-expression is evaluated again, and if it evaluates to
true
, statement
associated with the
for
-loop statement is executed and then the expression-list, and so on. This loop of execution
is repeated until the condition-expression evaluates to
false
. The execution of a
for
-loop statement is depicted in
Figure
5-2
.