Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on non-Ints in Java

Tags:

java

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?

like image 927
Adam Avatar asked Dec 04 '22 18:12

Adam


2 Answers

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.

like image 68
Paul Avatar answered Dec 15 '22 23:12

Paul


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

like image 37
Charlie Avatar answered Dec 16 '22 00:12

Charlie