【问题标题】:Is byte, short, char automatically promoted in switch statement?字节、短、字符是否在 switch 语句中自动提升?
【发布时间】:2016-05-22 19:37:54
【问题描述】:

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

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

}

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

提前感谢您的澄清。

问候, 丹尼尔

【问题讨论】:

  • switch 采用int 并且可以在需要时自动加宽字节、字符和short。

标签: java switch-statement type-promotion


【解决方案1】:

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

给定switch 语句,以下所有条件都必须为真,否则会发生编译时错误:

  • switch 语句关联的每个case 常量必须与switch 语句的表达式(第5.2 节)的类型兼容。

  • ...

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

【讨论】:

  • 谢谢@AR.3。很好的澄清。这是值得记住的一点:)
【解决方案2】:

是的,switch语句将生成tableswitch或lookupswitch原语,其常量通常根据this提升为int

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

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

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 2013-10-16
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多