Java Reference
In-Depth Information
switch( variable ){
variable =1
variable =2
case 1: ....
case 2: ....
variable = 3
case 3: ....
variable is not 1, 2, or 3
default ....
}
FIGURE 2.9:
The
switch
statement.
A
switch
statement can only be used to substitute a set of
if
statements that
check for
equality
. We cannot use an
if
statement to check for inequality (e.g.,
>
=3).
Java supports a
switch
statement only on variables of type
int
,
char
,and
String
.
Java does not support a switch statement on doubles.
A switch statement checks the value of the variable inside the parentheses. If it is equal
to the first case value, then the program jumps to this case and continues executing. Usually,
a
break
statement is put at the end of every
case
block in order to guarantee that only
one
case
statement is executed. For example, if the
break
statements are removed from the
above code and the user enters the string “A”, then all print statements will be executed.
The
break
statement exits out of the current
switch
statement and goes to the
first line immediately after the
switch
block. Usually, a
break
statement is required
at the end of each
case
blockinorderforthe
switch
statement to work properly.
A
break
statement is not required after the last
switch
block (assuming there is no
default
block) because the program exits the
switch
statement after that anyway.
Note that the
switch
syntax allows a
default
option. In the above code, if the input
string is not equal to
"A"
,
"B"
,
"C"
,
"D"
,or
"F"
, then only the last print statement will be
executed.
2.7 The Conditional Operator
It seems tedious to use an
if-else
construct even when we have a single line in both
the
if
and
else
blocks. In some cases, Java allows us to substitute the
if-else
statement