Java Reference
In-Depth Information
Two case labels in a
switch
statement cannot be the same. The following piece of code would not compile
because
case
label
10
is repeated:
int num = 10;
switch (num) {
case 10:
num++;
case 10: // A compile-time error. Duplicate case label 10
num--;
default:
num = 100;
}
It is important to note that the labels for each
case
in a switch statement must be a compile-time constant. That
is, the value of the labels must be known at compile time. Otherwise, a compile-time error occurs. For example, the
following code would not compile:
int num1 = 10;
int num2 = 10;
switch (num1) {
case 20:
System.out.println("num1 is 20");
case num2: // A Compile-time error. num2 is a variable and cannot be used as a label
System.out.println("num1 is 10");
}
You might say that you know the value of
num2
is 10 when the
switch
statement will be executed. However, all
variables are evaluated at runtime. The values of variables are not known at compile time. Therefore, the
case num2:
causes the compiler error. This is necessary because Java makes sure at compile time itself that all
case
labels are
within the range of the data type of the
switch-expression
. If they are not, the statements following those case labels
will never get executed at runtime.
■
Tip
the
default
label is optional. there can be at most one default label in a
switch
statement.
A
switch
statement is a clearer way of writing an
if-else
statement when the condition-expression in an
if-
else
statement compares the value of the same variable for equality. For example, the following
if-else
and
switch
statements accomplish the same thing:
// Using an if-else statement
if (i == 10)
System.out.println("i is 10");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is neither 10 nor 20");