Java Reference
In-Depth Information
of the first values will execute the first
statements
section, whereas values four and five will
execute the second
statements
section.
■
The
default
case is optional. If no default is given, it may happen that no case is
executed.
■
The
break
statement after the default (or the last case, if there is no default) is not needed
but is considered good style.
■
From Java 7, the expression used to switch on and the case labels may be strings.
Examples:
switch
(day) {
case
1: dayString =
"Monday"
;
break
;
case
2: dayString =
"Tuesday"
;
break
;
case
3: dayString =
"Wednesday"
;
break
;
case
4: dayString =
"Thursday"
;
break
;
case
5: dayString =
"Friday"
;
break
;
case
6: dayString =
"Saturday"
;
break
;
case
7: dayString =
"Sunday"
;
break
;
default
: dayString =
"invalid day"
;
break
;
}
switch
(dow.toLowerCase()) {
case
"mon":
case
"tue":
case
"wed":
case
"thu":
case
"fri":
goToWork();
break
;
case
"sat":
case
"sun":
stayInBed();
break
;
}
D.3
Loops
Java has three loops:
while
,
do-while
, and
for
. The
for loop
has two forms. Both
while
and
do-
while
are well suited for indefinite iteration. The for-each loop is intended for definite iteration
over a collection, and the for loop falls somewhere between the two. Except for the for-each
loop, repetition is controlled in each with a boolean expression.
Search WWH ::
Custom Search