Java Reference
In-Depth Information
Occasionally, we want to give up on the current iteration of a loop and go
on to the next iteration. This can be handled by using a
continue
statement.
Like the
break
statement, the
continue
statement includes a semicolon and
applies to the innermost loop only. The following fragment prints the first 100
integers, with the exception of those divisible by 10:
The
continue
state-
ment goes to the
next iteration of the
innermost loop.
for( int i = 1; i <= 100; i++ )
{
if( i % 10 == 0 )
continue;
System.out.println( i );
}
Of course, in this example, there are alternatives to the
continue
statement. However,
continue
is commonly used to avoid complicated
if-else
patterns inside loops.
1.5.8
the
switch
statement
The
switch
statement is used to select among several small integer (or character)
values. It consists of an expression and a block. The block contains a sequence of
statements and a collection of labels, which represent possible values of the
expression. All the labels must be distinct compile-time constants. An optional
default label, if present, matches any unrepresented label. If there is no applica-
ble case for the
switch
expression, the
switch
statement is over; otherwise, control
passes to the appropriate label and all statements from that point on are executed.
A
break
statement may be used to force early termination of the
switch
and is
almost always used to separate logically distinct cases. An example of the typical
structure is shown in Figure 1.5.
The
switch
state-
ment is used to
select among sev-
eral small integer
(or character)
values.
1.5.9
the conditional operator
The
conditional operator
?:
is used as a shorthand for simple
if-else
statements.
The general form is
The
conditional
operator
?:
is used
as a shorthand for
simple
if-else
statements.
testExpr
?
yesExpr
:
noExpr
testExpr
is evaluated first, followed by either
yesExpr
or
noExpr
, producing
the result of the entire expression.
yesExpr
is evaluated if
testExpr
is
true
;
otherwise,
noExpr
is evaluated. The precedence of the conditional operator is
just above that of the assignment operators. This allows us to avoid using
parentheses when assigning the result of the conditional operator to a vari-
able. As an example, the minimum of
x
and
y
is assigned to
minVal
as follows:
minVal = x <= y ? x : y;
Search WWH ::
Custom Search