Right, it works if the variable is a constant and its value fits into the switch variable type. But in general, byte can have a negative values and so the range of a byte is not compatible with a char. That is why switch expression of type char and case label value of type byte will not work.
This is very different from "switch expression of type int and case label value of type char." All char values are assignable to an int, so there is no issue here. Any char label will work if the switch variable is of type int.
So, the two situations are different. You cannot say that if the first is correct then the second must be correct as well.
If you like our products and services, please help us by posting your review here.
I believe the answer "switch expression of type int and case label value of type char." should actually be written as "switch expression of type char and case label value of type int.".
No, it is correct as it is. "switch expression of type char and case label value of type int" would be a wrong option because it is not valid for all situations as shown below:
int i = 97;
char ch = 'a';
switch(i){
case 'a' : System.out.println("got a");//any char value is valid here because all char values are assignable to an int variable.
}
switch(ch){
case 97 : System.out.println("got 97"); //This is ok.
case -1 : System.out.println("what?"); //This will NOT compile because -1 is not a valid value for a char.
}