Could someone please explain why in K&B's book on page 219 the code at the bottom causes an error, which I'll repeat here for those not using the book?
the error says possible loss of precision found: int required: byte case 128: But on the previous page it says switch only evaluates primitive int, so the way I see it, g, would implicitly be cast as an int when used in the switch statement and you would be comparing an int to 128 which I take to be an int. Could someone please clear this up for me? Thanks
I don't have the K & B book (wish I'd bought it!), but I think it means that the valid parameter types for a switch statement must be int or anything that is a widening conversion to an int. So, no booleans or floating points are allowed. This is a bit of a tricky question in that the compiler compares the max value of the switch type with the argument for each case statement. Here, the max value of a byte is 127, so the compiler complains about 128.
SCJP 1.4, SCWCD 1.3, SCBCD 1.3
Joined: Apr 01, 2003
Roger, Does evaluate primitive int imply that it can evaluate anything that can be widened to an int, BUT maintains the type such as byte in this case, or does it actually do the conversion thus comparing ints now not bytes?
According to me the way the compiler sees this is "you won't be able to have a value in the switch(value) which will be greater than 127 or less that -128 so I will flag a compile time error if you try to do so". [ May 17, 2003: Message edited by: Anupam Sinha ]
Joined: Apr 01, 2003
Yes but the value is 2 which falls within the byte range, the problem is in the case statement. And if the byte in the switch is implicitly cast to an int this should not be a problem. Which is why I don't follow what is wrong.
Ah yesss - one of the most missed questions in my Hardest collection. The requirement is that the variable used in a switch statement MUST be capable of having all of the values that appear in case statements. THEREFORE - if the variable is a byte, you can't have case constants outside the byte range minus 128 thru plus 127. If the variable is a char, you can't have any negative values. This is supposed to be enforced by the compiler, although we did find one IBM compiler version that did not. Bill