aspose file tools
The moose likes Java in General and the fly likes Switch Case constants Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Switch Case constants " Watch "Switch Case constants " New topic
Author

Switch Case constants

MukulJ Patil
Greenhorn

Joined: Sep 18, 2006
Posts: 6
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
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
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
See there is a big difference b/w



and a

vitthal wable
Greenhorn

Joined: Sep 09, 2006
Posts: 16
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
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
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 ]

Tony Morris
Java Q&A (FAQ, Trivia)
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Sorry about the link screw up - fixed now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch Case constants
 
Similar Threads
Switch statement and constant variables
assignment problem
doubt regarding switch() case construct for flow control
a query about switch
Compile Time Constant