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

1.6k Views Asked by At

Given the following code, is 'a' (that is of type char) automatically promoted to int type in switch-case statement?

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

}

I couldn't find whether Java SE7 mentions about that..

Thanks in advance for clarification.

Regards, Daniel

2

There are 2 best solutions below

1
On BEST ANSWER

Here's what the language specification mentions about this. See 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).

  • ...

which means that a narrowing conversion will apply to the char value 'a'. Its numeric value of 97 is representable as a byte. The value 256 however does not fit so the compiler will throw an error.

0
On

Yes the switch statement will generate tableswitch or lookupswitch primitives with constants which are promoted to int generally according to this

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

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