aspose file tools*
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 19538
    
  16

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: final variable in switch case
 
Similar Threads
what is compile time constant in switch case?
Final variables in switch
final variable declaration
Complie time Constant - final int a; a =1 ; IS NOT?!
Doubt about Switch statement (Compile Time Constant)