This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
case label in Switch needs compile time constant expression
Posted by Kishori Sharan on January 11, 2001 at 10:44 AM
The expression used in case label in switch statement must be a compile time constant expression. I mean its value must be determined at compile time so that Java Compiler can make sure all case values in switch statmenet fall within the range of expression type used in switch.
When you use base variable to initialize SOME_NOTIFICATION then SOME_NOTIFICATION becomes run time constant even if it is declared final because the value of base cannot be determined at compile time( it seems base has a value of zero though ). If you rephrase your initialization like
private static int base = 0;
public static final int SOME_NOTIFICATION = base++;
If you rephrase your initialization like
private static final int base = 0;
public static final int SOME_NOTIFICATION = base + 1 ;
then it will compile fine because SOME_NOTIFICATION is a compile time constant.
There is no other way of getting switch statement straight than using a compile time constant expression for case.
I am attaching the definition of a compile time constant expression from java Language Specification for your info.
/////////Compile time constant
A compile-time constant expression is an expression denoting a value of primitive type or a String that is composed using only the following:
Literals of primitive type and literals of type String
Casts to primitive types and casts to type String
The unary operators +, -, ~, and ! (but not ++ or --)
The multiplicative operators *, /, and %
The additive operators + and -
The shift operators <<, >>, and >>>
The relational operators <, <=, >, and >= (but not instanceof)
The equality operators == and !=
The bitwise and logical operators &, ^, and |
The conditional-and operator && and the conditional-or operator ||
The ternary conditional operator ? :
Simple names that refer to final variables whose initializers are constant expressions
Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions