Java Reference
In-Depth Information
throw new NonHexDigitException(ch);
}
}
There are no
break
statements because the
return
statements exit the
switch block (and the whole method) before control can fall through.
You should terminate the last group of statements in a switch with a
break
,
return,
or
throw
, as you would a group of statements in an earlier
case. Doing so reduces the likelihood of accidentally falling through the
bottom of what
used
to be the last part of the switch when a new
case
is
added.
All
case
labels must be enum constants or constant expressionsthe ex-
pressions must contain only literals or named constants initialized with
constant expressionsand must be assignable to the type of the
switch
expression. In any single
switch
statement, each
case
value must be
unique, and there can be at most one
default
label.
When you use an enum as a switch expression, you will get no warning if
you leave out a case. It is your job to ensure that each case is covered.
To safeguard against an enum being redefined to have additional con-
stants, you should always include a
default
case that simply throws an
exception.
Only statements directly within the switch block can have
case
labels.
This means that you cannot, for example, transfer control to a state-
ment within the switch block that is in the middle of a loop, or a state-
ment within a nested block of code. You can, however, skip the declar-
ation and initialization of a local variable within the switch block (not
that we recommend it). The effect of this is that the local variable is still
considered to be declared, but the initializer has not been executed. Be-
cause local variables must be initialized, any attempt to read the value
of that variable will result in a compile-time errorthe first use of that
variable must be an assignment.