Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variable in switch case

 
MaheshS Kumbhar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Raju Goke
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic