Here's an excerpt from Sun's Java tutorials:
A switch works with the
byte
,short
,char
, andint
primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types:Character
,Byte
,Short
, andInteger
(discussed in Simple Data Objects).
There must be a good reason why the long
primitive data type is not allowed. Anyone know what it is?
Java Wrapper in Switch StatementJava allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1.
The value for a case must be of the same data type as the variable in the switch. The value for a case must be constant or literal. Variables are not allowed.
I think to some extent it was probably an arbitrary decision based on typical use of switch.
A switch can essentially be implemented in two ways (or in principle, a combination): for a small number of cases, or ones whose values are widely dispersed, a switch essentially becomes the equivalent of a series of ifs on a temporary variable (the value being switched on must only be evaluated once). For a moderate number of cases that are more or less consecutive in value, a switch table is used (the TABLESWITCH instruction in Java), whereby the location to jump to is effectively looked up in a table.
Either of these methods could in principle use a long value rather than an integer. But I think it was probably just a practical decision to balance up the complexity of the instruction set and compiler with actual need: the cases where you really need to switch over a long are rare enough that it's acceptable to have to re-write as a series of IF statements, or work round in some other way (if the long values in question are close together, you can in your Java code switch over the int result of subtracting the lowest value).
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