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 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
would also fail to compile.
See the Java Language Specification