Basically this is an error that generally occurs when java is not able to verify the constant nature of expression even if it appears constant in your code.Switch statement in java requires that case labels are compile time constants
For Foo.BAR, Foo.BAZ, and Foo.BAM to be used in a switch statement, they must be assigned their values directly. Here’s how you can modify your class:
java
public abstract class Foo {
public static final int BAR = 1;
public static final int BAZ = 2;
public static final int BAM = 3;
}
With the constants explicitly assigned values, you can use them in your switch statement without any errors:
java
public static String lookup(int constant) {
switch (constant) {
case Foo.BAR: return "bar";
case Foo.BAZ: return "baz";
case Foo.BAM: return "bam";
default: return "unknown";
}
}
If BAR, BAZ, and BAM need to be computed or set in some non-constant way, they won’t qualify for use in a switch statement. In that case, an if-else construct would be more appropriate.