Forums Register Login

Legal Expression for Switch....

+Pie Number of slices to send: Send

Can someone tell me why long, float and double are not allowed in Switch's expression and only the char, byte, short, int and Enum are allowed?

Thanks..
+Pie Number of slices to send: Send
Actually, Strings are allowed, but only in Java7.

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.
+Pie Number of slices to send: Send
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!
1
+Pie Number of slices to send: Send
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.
Yes, my master! Here is the tiny ad you asked for:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 954 times.
Similar Threads
Numeric/Alphabetic chars
Empty id attribute is not allowed
return value
about switch case
when private is not so private
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:50:58.