Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch expression can't be float, double or boolean

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?

like image 682
saravanan Avatar asked Feb 28 '11 12:02

saravanan


People also ask

Can we use float and double in switch-case?

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.

Can switch statement takes boolean?

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.

Can we use float in a switch statement?

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.

Can your switch statement accept long double or float data type?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.


2 Answers

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?

like image 150
Jon Skeet Avatar answered Sep 29 '22 03:09

Jon Skeet


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.

like image 42
Peter Lawrey Avatar answered Sep 29 '22 03:09

Peter Lawrey