Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final in switch case

 
sarathchandra chandala
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Test
{
public static void main(String[] args)
{
final int a = 1;
final int b;
b = 2;
int x = 0;
switch (x) {
case a: // ok
case b: // compiler error
}
}
}
Please explain me why the above code is giving error
 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
generally speaking, it is of TREMENDOUS help if you post the actual text of the error message. without it, we either have to guess, or copy your code and compile it ourselves. The easier you make it for others to help you, the more likely you are to get help.
 
Bill Shirley
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also, use code tags



after this line of code the value of b can never be changed,
it is therefore undefined

what's the next line of code?
[ January 24, 2008: Message edited by: Bill Shirley ]
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bill Shirley:
also, use code tags



after this line of code the value of b can never be changed,
it is therefore undefined

what's the next line of code?

[ January 24, 2008: Message edited by: Bill Shirley ]


Not entirely true.
You can delay the inital assignment of a final variable.

Example:
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Values we use in switch cases must be "COMPILE TIME CONSTANT"

In your case a is defined at the compile time, but for b it is initialize at the run time..!!

Since both a and b are local Variable, following checks are done by compiler :

1) Variable are initialize before using
2) In case of final variable, see after initialization there should not be any probability of changing their value..!!

In this case compiler checks that Variable b has been given a value, but that value will be assigned at run time..so it is giving an error because it wants value at the compile time...!!
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using anything except literals or "static final" constants as switch cases is very bad form. So, while you do seem to have found a situation where the compiler is being a bit dimmer than one might hope, its real-world relevance is very slight indeed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic