If you have
it runs fine. Note that the switch expression is of type short (2 bytes) and the case constant is of type int (4 bytes).
My question is: Is the type irrelevant as long as the value is within the boundaries of the type of the switch expression?
I have the feeling that this is true since
this runs fine again, but if I change the literal assigned to i to 128, which is out of range for type byte, then the compiler complains.
Is it true that in the first example the short variable and in the second example the byte variable (the switch expressions) are first implicitly converted to an int and then compared with the case constants?
Thanks for the answer... In future I'll try not to get hung up on every little question mark that pops up in my head!
Also tell us the full details; where was the compiler error? Was it about exceeding the range of a byte or about the switch statement?
This is what I get when in the example I replace the literal at line 02. with the literal 128. It was about the exceeding range of a byte.
(Of course, since 128 is out of range for a byte)
But after having read the FAQ 'Don't sweat it' I don't think it's *that* important to know *every* little detail about Java there is... my primary goal for now is - as it says in the FAQ - to become a good Java programmer...
I think I found the solution in the Java Language Specification about the switch statement:
All of the following must be true, or a compile-time error occurs:
Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
No two of the case constant expressions associated with a switch statement may have the same value.
No switch label is null.
At most one default label may be associated with the same switch statement.
It says here that the "case constant expression" must be assignable to the type of the switch statement... I conclude that only the literal counts that comes out of the "case constant expression"... and that literal has to be within the bounds of the type of the switch expression... thus the type of the "case constant expression" doesn't really matter... only its value.