We are going to the Java language specification. A switch case expression labels are defined as
SwitchLabel: case ConstantExpression : case EnumConstantName : default :
Your num variable does not apply to the enum constant name, so let it ignore it. What are ConstantExpressions ? JLS defines it again
The compile-time constant expression is an expression denoting a value of a primitive type or String , which does not end abruptly and using only the following:
- Primitive type literals and String literals
- [...]
- Simple names (Β§6.5.6.1) that refer to constant variables (Β§4.12.4).
So, the primitive value of int 2 is a constant expression. You could do
switch { case 2: }
Now we want to find out the relation using final and a constant variable .
Empty final is the final variable, in the declaration of which there is no initializer. [...]
A variable of a primitive or String type, that is, final and initialized by the expression of a compile-time constant (Β§15.28), is called a constant variable.
Thus, the last quote refers to a non-empty variable final , i.e. one that has an initializer.
So
final int num1 = 1;
is a constant variable.
and
final int num2; num2 = 2;
not used and therefore cannot be used in the case label.
Sotirios delimanolis
source share