Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch case with final

 
kalpana Kumar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
In the following code
public static void main(String args[]){
final int a=1;
final int b;
b=20;//is this b not final
int x=0;
switch(x){
case a:
case b: //compiler error


}
}
I want clarification as to why is b not considered to be a compile time constant???.

Thanks
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not a constant because it can be changed. The compiler does not know whether or not you will change it, but it knows that it might be changed because it is not final.
 
kalpana Kumar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marilyn,
Thanks a lot for the response.
But in the above code b is defined to be final. it is initialised in the next line.
I wanted to know if there is any difference in this type of initialization.

Thanks
 
Brian Cole
Author
Ranch Hand
Posts: 903
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kalpana Kumar:
final int a=1;
final int b;
b=20;//is this b not final


Both a and b are final, but a is declared with an initializer
that is a constant expression. b is declared as blank final.

Originally posted by kalpana Kumar:
But in the above code b is defined to be final. it is initialised in the next line.
I wanted to know if there is any difference in this type of initialization.


Yes there is. Here are two pointers into the JLS you can
take a look at:

constant expressions (see the last two items in the bulleted list)

definite assignment of blank finals
[ November 06, 2005: Message edited by: Brian Cole ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have confused a constant with a final.
A final is not always a constant, but a constant is always final.
Your issue is related to constants, not finals.
This is why you observe some finals, that are not constants, behaving differently to other finals, that are constants.

The links above are your point of call (JLS 15.28 and JLS 16).
Here is some fun: http://jqa.tmorris.net/trivia/GetQAndA.action?qids=13
 
kalpana Kumar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for all the replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic