This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Presumably because whoever designed the language (well, actually Kernighan and Ritchie, because the construct is inherited from C) thought it was reasonable to have case 1: case 2: but not case 1.1: case 1.2:
We can never be certain unless we find an explanation from those people. See if you can find a copy of the C Programming Language by Kernighan and Ritchie, and whether there is an explanation in there.
Joined: Oct 13, 2005
A long would be pointless; by the time you have provided enough case 123456789: labels to exhaust the capacity of the int primitive datatype, you will have exhausted the RAM capacity of your computer!
The reason why you can't use float and double is because these data types do not have infinite precision. It's almost never a good idea to make exact comparisons involving floating point numbers. Try this:
What do you think this will print?
So, it does not make much sense to allow using float and double in switch statements (where the value you are switching on is exactly compared to the case values).
A reason why long is not allowed is probably because of how the switch statement is implemented under the covers. Compilers often generate a branch table, which is an efficient way for the computer to do a switch. However, for technical reasons, it wouldn't be so efficient if a long would be used. Admittedly, this argument is a bit weak, there's no real reason why it shouldn't be possible or a good idea to allow long to be used in switch statements - the compiler could just as well allow it and convert it to something less efficient, but the Java language designers just chose not to do that.
@Campbell: Using a long doesn't automatically imply that you'd want to create millions of cases in the switch statement.