Why Java Switch Cannot Use long and How enum, String, and Primitive Types Are Compiled to int
The article explains why Java's switch statement cannot handle long values, detailing how enum, String, and primitive types are internally converted to int via compiler‑generated tables and hashCode logic, and includes decompiled examples illustrating this behavior.
Java's switch statement historically supported byte, short, int, and later added enum (JDK 1.5) and String (JDK 1.7), but it cannot handle long because the compiler implements switch by translating the case values to an int‑based jump table.
Both enum and String cases are ultimately converted to int values. For enums the compiler generates a synthetic $SwitchMap array that maps each enum constant's ordinal() to a unique int, and the switch operates on that array.
Example enum definitions:
public enum SexEnum {
MALE(1, "男"),
FEMALE(0, "女");
private int type;
private String name;
SexEnum(int type, String name) { this.type = type; this.name = name; }
}
public enum Sex1Enum {
MALE("男"),
FEMALE("女");
private String name;
Sex1Enum(String name) { this.name = name; }
}A test class demonstrates the generated switch logic:
public class SwitchTest {
public int enumSwitch(SexEnum sex) {
switch (sex) {
case MALE: return 1;
case FEMALE: return 2;
default: return 3;
}
}
public int enum1Switch(Sex1Enum sex) {
switch (sex) {
case FEMALE: return 1;
case MALE: return 2;
default: return 3;
}
}
}Decompiled bytecode shows the $SwitchMap arrays and the int‑based switch on sex.ordinal() , confirming that the original enum values are reduced to ints.
For char and primitive types, the switch uses the character's Unicode (ASCII) value directly. For String cases the compiler first computes hashCode() , uses a temporary int variable, and resolves hash collisions with equals() before switching on the resolved int.
Wrapper types such as Integer, Character, and Byte are also supported because the compiler inserts an automatic unboxing call (e.g., c.intValue() ) before the int‑based switch. Passing a null wrapper results in a NullPointerException.
The article also contains promotional notes for a WeChat public account and a giveaway, but the technical explanation of Java switch compilation remains the core content.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.