Why is this int switch valid:
public class Foo {
private final static int ONE = 1;
private final static int TWO = 2;
public static void main(String[] args) {
int value = 1;
switch (value) {
case ONE: break;
case TWO: break;
}
}
}
While this enum switch is not:
import java.lang.annotation.RetentionPolicy;
public class Foo {
private final static RetentionPolicy RT = RetentionPolicy.RUNTIME;
private final static RetentionPolicy SRC = RetentionPolicy.SOURCE;
public static void main(String[] args) {
RetentionPolicy value = RetentionPolicy.RUNTIME;
switch (value) {
case RT: break;
case SRC: break;
}
}
}
I know that what goes in the case must be a constant, so why can I use a "final static int" as constant but not a "final static <your enum>"?
Because a case statement label must have either a compile time constant or an EnumConstantName. JLS 14.11
Compile time constants can only be strings and primitive types, as described by JLS 15.28. Thus you can not use a static final <your enum>, as it is neither a compile time constant, nor the name of an enum.