• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Legal Expression for Switch....

 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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..
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic