permaculture playing cards*
The moose likes Beginning Java and the fly likes Legal Expression for Switch.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Legal Expression for Switch...." Watch "Legal Expression for Switch...." New topic
Author

Legal Expression for Switch....

Mihir Patel
Greenhorn

Joined: Apr 26, 2011
Posts: 18


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

Joined: Oct 13, 2005
Posts: 38463
    
  23
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

Joined: Oct 13, 2005
Posts: 38463
    
  23
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

Joined: Aug 16, 2005
Posts: 14114
    
  16

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Legal Expression for Switch....