I'm having trouble figuring out the inner workings of switches in Java I'm told that for all primitives, the value is promoted to a Integer.
However, in the following example, I'm testing on a byte variable, and any case larger than 127 will not compile:
byte k = 5;
switch(k){
case 128: //fails to compile, possible loss of precision
I realize this is an error and have no issue with that. My question is:
How does the JVM track that it's switching on a byte if it takes the value of "k" and promotes it to an integer before testing each case?
The switch
statement is not limited to int
. The Java Language Specification (JLS), section 14.11, The switch Statement, states
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.
Your byte
, therefore, is not promoted to an int
. The JLS goes on to say that what you are doing will cause a compile-time error:
Every case constant expression associated with a switch statement must be assignable to the type of the switch Expression.
...since 128 is not assignable to a byte
.
The problem is it's not promoting the value of k, it's trying to take the case statement (128 - signed integer) and assign it to a byte. As 128 is larger than 1 byte (7 bits + sign bit) then the compilation fails.
For example
byte k = 128;
would also fail to compile. See the Java Language Specification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With