Java的switch-case与C中的switch-case基本一致,但还是有些地方需要注意的。
switch-case语句的一般形式为:
switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}
(1) A switch's expression must evaluate to a char, byte, short, int, or an enum.
(2)The case constant must be a compile time constant!
特别要注意第二点,case后边跟的不但是常量而且必须是编译时的常量,任何运行是的常量都会产生compiler error。
如下代码:
public class Switch {
public static void main(String[] args) {
final int a = 1; //the value of a is known at compile time
final int b; //the value of b is known at run time, it must be initialized before used, and the compiler ensures this
b = 2;
int x = 0;
switch (x) {
case a:
case b:
}
}
}
编译时出现错误:
当switch的表达式是char、byte、short时会自动提升为整型(int)。switch表达式必须是可以自动提升为int型的类型,即char、byte、short、int,除此之外枚举enum也可以是switch的表达式。
提到enum,Java的枚举和C的枚举在语法上有些不同之处,经常弄混。
如下Java代码:
enum Color {
RED, GREEN, BLACK, //最后一个后面可以是逗号、分号,也可以什么也没有
}
public class Enum {
public static void main(String[] args) {
Color c = Color.RED;
Color c2 = RED; //compiler error
switch (c) {
case Color.RED : //compiler error
case GREEN :
default :
}
}
}
编译时出现如下错误:
如下C代码:
#include <stdio.h>
int main(void)
{
enum Color {
RED, GREEN, BLACK, //最后一个之后可以是逗号也可以什么都没有,但不能是分号
};
enum Color c = RED; //不存在c.RED、c.GREEN,与结构体和联合不同
switch (c) {
case RED :
case RED :
}
return 0;
}