This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes final variable in switch case Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "final variable in switch case" Watch "final variable in switch case" New topic
Author

final variable in switch case

MaheshS Kumbhar
Ranch Hand

Joined: Sep 24, 2009
Posts: 188
class testSwitch
{
public static void main(String[]s){
final int a,x=1;
a=10;
switch(x)
{
case a:
}
}
};

In above code sample, I get compilation fail error that constant expression required in switch case, why is it so though variable a is declared to be final.


I am slow but sure
Raju Goke
Greenhorn

Joined: May 01, 2007
Posts: 7
MaheshS Kumbhar wrote:class testSwitch
{
public static void main(String[]s){
final int a,x=1;
a=10;
switch(x)
{
case a:
}
}
};

In above code sample, I get compilation fail error that constant expression required in switch case, why is it so though variable a is declared to be final.


Hi,

You should initialize the final variables at the time of declaration only. Declare the variable as follows:

final int a=10,x=1;
---
---

Regards,
Raju
MaheshS Kumbhar
Ranch Hand

Joined: Sep 24, 2009
Posts: 188
Ya, initializing the final variable at the time of declaration resolves the issue. But what causes the compiler to spit an error if we dont initialize the final variable at the time of declaration.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

Because the compiler cannot associate "i" with "10" at compile time; it can only do this when the variable is initialized when declared. This has something to do with how the source code is parsed and all.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: final variable in switch case
 
Similar Threads
Final variables in switch
what is compile time constant in switch case?
final variable declaration
Doubt about Switch statement (Compile Time Constant)
Complie time Constant - final int a; a =1 ; IS NOT?!