Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't your switch statement data type be long, Java?

Here's an excerpt from Sun's Java tutorials:

A switch works with the byte, short, char, and int 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, and Integer (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?

like image 227
Fostah Avatar asked Apr 20 '10 15:04

Fostah


People also ask

Can long be used in switch statement in Java?

Java Wrapper in Switch StatementJava allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Which datatype is not allowed in switch-case?

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

Can it be a long in Java?

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.

Which data type is not used in switch-case in Java?

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.


1 Answers

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).

like image 180
Neil Coffey Avatar answered Oct 13 '22 09:10

Neil Coffey