Switch with Primitive Types: int, byte, short, char
You'll learn which primitive types work with switch statements and why smaller integer types are automatically promoted.
The Compatible Types
Not all primitive types work with switch statements. Java's switch accepts these four primitive types:
int— the standard integer typebyte— automatically widened tointshort— automatically widened tointchar— automatically widened toint
Notice what's missing: long, float, double, and boolean do not work with switch.
Why These Four?
The switch statement was designed for discrete, hashable values that can be efficiently compared. Behind the scenes, Java converts byte, short, and char to int through widening conversions (which you learned earlier). This happens automatically and safely because no data is lost when promoting smaller integer types to int.
byte level = 2;
switch (level) { // byte automatically widened to int
case 1:
// handle level 1
break;
case 2:
// handle level 2
break;
}
char grade = 'B';
switch (grade) { // char treated as its numeric value
case 'A':
// excellent
break;
case 'B':
// good
break;
}
Why Not long, float, or double?
These types would make comparison inefficient or ambiguous. Floating-point equality is imprecise, and long wasn't initially supported (though modern Java added String and enums, it still excludes long for historical reasons).
Key Takeaway: The switch statement works with int, byte, short, and char — all types that can be safely widened to int for efficient comparison. Other primitives like long, float, double, and boolean are not supported.