A TL;DR is at the end.
Looking into the documentation of the switch statement we can find the following:
A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
At first this seems fine and your problem shouldn't exist. However the definition does not mention where those wrappers can be used and where not. Looking into the specs of the switch-statements (JLS) we find that a switch has the form of:
1 Switch-Expression
SwitchStatement:
switch ( Expression ) SwitchBlock
The Expression
is further explained:
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
So here, it's totally fine to use a wrapper class such as Integer
. The compiler will manage.
2 Switch-Block
The switch-block can be broken down into:
SwitchLabels BlockStatements
The SwitchLabel
is defined as:
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
So a label will only accept constant expressions or enums. If we now have a look at the definition of a constant expressions, we'll find:
A constant expression is an expression denoting a value of primitive type or a String...
Of course some conditions have to apply to make primitive type a constant (it is listed there) but in your case the important part is that you have to use a primitive type or a String.
BONUS
The exchange between wrapper class and primitive type is called "autoboxing or unboxing" (depending on the direction). According to the documentation, unboxing takes place when:
Converting an object of a wrapper type (Integer
) to its corresponding primitive (int
) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:
- Passed as a parameter to a method that expects a value of the
corresponding primitive type.
- Assigned to a variable of the
corresponding primitive type.
So it seems like Java is simply not built to to make the required unboxing in order for the switch-statement to work, as you intended.
----------------------
TL;DR
For the switch expression you can use the wrapper class. For the labels however you can only use the primitive types: byte, short, char and int.