byte, short, char 是否在 switch 语句中自动提升?

Is byte, short, char automatically promoted in switch statement?

给定以下代码,是'a'(即类型char) 在 switch-case 语句中自动提升为 int 类型?

void testSwitch(byte x) {
    switch(x) {
       case 'a':   // 1
       case 256:   // 2
       default:   //  3
       case 1:    //  4
    }

}

我找不到 Java SE7 是否提到了这一点..

提前感谢您的澄清。

此致, 丹尼尔

这是语言规范中提到的内容。见 this section on switch statements:

Given a switch statement, all of the following must be true or a compile-time error occurs:

  • Every case constant associated with the switch statement must be assignment compatible with the type of the switch statement's Expression (§5.2).

  • ...

这意味着缩小转换将应用于 char'a'。它的数值 97 可以表示为 byte。然而,值 256 不适合,因此编译器将抛出错误。

是的,switch 语句将生成带有常量的 tableswitch 或 lookupswitch 原语,这些常量通常根据此

http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html

Why does the Java API use int instead of short or byte?