Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch- Case doubt in case expressions.

 
Ramesh Ponnada
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





Question:

Both variables a and b are compile time constants as they are declared as final, even then why Compiler is complaining this way.
[ December 19, 2007: Message edited by: Ramesh Ponnada ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ramesh Ponnada:





Question:

Both variables a and b are compile time constants as they are declared as final, even then why Compiler is complaining this way.

[ December 19, 2007: Message edited by: Ramesh Ponnada ]


They are not compile-time constants.

In the first case, c is not assigned a value until the class definition is loaded into memory the first time.

In the second case, both a and c are instance variables so each instance of the class gets their own copy.
 
Sergey Petunin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Declaring a variable as final doesn't make it a compile-time constant.

According to the Java Language Specification, compile-time constant has to be initialized with the compile-time constant expression, which means that it has to have an initializer right where it's declared.

That's why in the first case "a" is a compile-time constant, and "c" is not.

Also, according to JLS, a compile-time constant may be composed of a simple name that refers to a constant variable or a qualified name of the form TypeName.Identifier that refers to a constant variable.

So in the second case you're using s.a and s.c, where s is not a type name, it's an instance name, so those are not compile time expressions.
 
Cory Max
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Serge. If you substituted s. with Sample and set your var's when they were declared, the code would definitely compile.

 
Ramesh Ponnada
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys,

Explanation really helped in understanding what are compile time constants.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic