I am trying to compile following program but it's giving error- that "Switch case constants must be Compile time constants!" This can be removed by declaring & initialising the final variable on the same line. But i am doing declaration & initialisation on two different lines. I don't know the difference between these two. Please explain. public static void main(String[] args) { final int a=0; final int b; b=10; int x=0; switch(x) { case a: System.out.println("ok1"); break; case b: System.out.println("ok2"); break; // Error over here. } }
Pradeep Kadambar
Ranch Hand
Joined: Oct 18, 2004
Posts: 148
posted
0
Hi Mukul,
Your code would compile fine if suppose you do something like
If b is not constant then it may change over the course of execution ! which is not intended. So you always need to have constant or expressions that can be evaluated at compile time.
But in your code
MukulJ Patil
Greenhorn
Joined: Sep 18, 2006
Posts: 6
posted
0
I know how to make it compile. But my question is what is the difference in the two types of declarations?
Pradeep Kadambar
Ranch Hand
Joined: Oct 18, 2004
Posts: 148
posted
0
See there is a big difference b/w
and a
vitthal wable
Greenhorn
Joined: Sep 09, 2006
Posts: 16
posted
0
Hii, You are Using variable which are initialize at execution time , that is isintialize at run time, As switch requires the variable which are initialized compile time means declared and initialized on same line
MukulJ Patil
Greenhorn
Joined: Sep 18, 2006
Posts: 6
posted
0
Guys, Thanks. But you all are talking about the things that i have already stated. I am interested in knowing why there is such difference in two forms of declaration? In both cases, i am initialising the variable. Then why it causes the compiler to treat the two line declaration as runtime initialisation?
Tony Morris
Ranch Hand
Joined: Sep 24, 2003
Posts: 1608
posted
0
Because one is a constant and one is not. The definition of a constant is given in JLS3 15.28. You might also find this interesting: When a final is not a constant [ September 19, 2006: Message edited by: Tony Morris ]