| Author |
Switch- Case doubt in case expressions.
|
Ramesh Ponnada
Greenhorn
Joined: Nov 05, 2004
Posts: 18
|
|
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 ]
|
Thanks<br />Ramesh <br />SCJP 5.0 | SCWCD 5.0
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
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
Joined: Dec 16, 2007
Posts: 44
|
|
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
Joined: Jul 20, 2005
Posts: 83
|
|
I agree with Serge. If you substituted s. with Sample and set your var's when they were declared, the code would definitely compile.
|
There are only 10 types of people in this world... Those who understand binary and those who don't.
|
 |
Ramesh Ponnada
Greenhorn
Joined: Nov 05, 2004
Posts: 18
|
|
Thanks guys, Explanation really helped in understanding what are compile time constants.
|
 |
 |
|
|
subject: Switch- Case doubt in case expressions.
|
|
|