Why doesn't the switch
expression allow long
, float
, double
or boolean
values in Java? why is only int
(and those that are automatoically promoted to int
) allowed?
Usually switch-case structure is used when executing some operations based on a state variable. There an int has more than enough options. Boolean has only two so a normal if is usually good enough. Doubles and floats aren't really that accurate to be used in this fashion.
The switch statement is one of the more syntactically complicated expressions in Java. The expression in the switch statement must be of type char, byte, short, or int. It cannot be boolean, float, double, or String.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
Float and double would be awkward to use reliably even if they were possible - don't forget that performing exact equality matches on float/double is usually a bad idea anyway, due to the nature of the representation.
For Boolean values, why not just use if
to start with?
I can't remember ever wanting to switch on any of these types, to be honest. Do you have a particular use case in mind?
You can use enum
in a switch statement and Java 7 will add String AFAIK. The switch statement comes from C where only int's were allowed and implementing other types is more complicated.
Floating point numbers are not a good candiates for switch as exact comparison is often broken by rounding errors. e.g. 0.11 - 0.1 == 0.01
is false.
switch on boolean is not much use as a plain if
statement would be simpler
if(a) { } else { }
would not be simpler with
switch(a) { case true: break; case false: break; }
BTW: I would use switch(long) if it were available, but its not. Its a rare use case for me any way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With