Java Reference
In-Depth Information
Examples:
if
(field.size() == 0) {
System.out.println(
"The field is empty."
);
}
if
(number < 0) {
reportError();
}
else
{
processNumber(number);
}
It is very common to link if-else statements together by placing a second
if-else
in the
else
part of the
first. This can be continued any number of times. It is a good idea to always include a final
else
part.
if
(n < 0) {
handleNegative();
}
else if
(number == 0) {
handleZero();
}
else
{
handlePositive();
}
D.2.2 switch
The
switch statement
switches on a single value to one of an arbitrary number of cases. Two
possible patterns of use are:
switch
(
expression
) {
switch
(
expression
) {
case
value
:
statements
;
case
value1
:
break
;
case
value2
:
case
value
:
statements
;
case
value3
:
break
;
statements
;
further cases possible
break
;
default
:
statements
;
case
value4
:
break
;
case
value5
:
}
statements
;
break
;
further cases possible
default
:
statements
;
break
;
}
Notes:
■
A
switch
statement can have any number of
case
labels.
■
The
break
statement after every case is needed, otherwise the execution “falls through” into
the next label's statements. The second form above makes use of this. In this case, all three
Search WWH ::
Custom Search