This question is related to one of the questions in Dan Chisholm's Single Topic Exams. In the following code:
He refers to char c in method m1() as a compile time constant. However, the final char c in the argument list of method m3() is not a compile-time constant. I thought that a variable's being declared final would make it a compile-time constant. Any other factors invovled here? Thanks, Saket
A simple name that refers to a final variable whose initializer is a constant expression. The formal parameter declaration final char c of the method m3 does not have an initializer. JLS 15.28 Constant Expression (last section) defines compile-time constant expressions.
I want to make sure that the point of this code. Since third and forth methods do not have final values at compile time, their return value should be casted to fit in the return type. Is this correct?
"Is this correct?" almost "Since third and forth methods do not have final values at compile time," - well... I think you understand, but let's work on the explanation... The variables c and s are declared final, but they do not have initializers that are constants. Therefore, they are not compile-time constants. "their return value should be casted to fit in the return type." - Yes. final char c; //c is not a compile-time constant final char d = 10; //d is a compile-time constant final char e = c + 1; //e is not a compile-time constant final char f = d + 2; //f is a compile-time constant void m(final char g) {} //g is not a compile-time constant [ May 31, 2003: Message edited by: Marlene Miller ]
byte m(final char c) { return c; } //compiler-error c is declared final. The reason c is not a compile-time constant is that the declaration of c does not have an initializer that is a constant expression. What a crummy explanation. Here is a more intuitive explanation. The reason c is not a compile-time constant is that the compiler cannot know at compile-time what the value of c is. [ May 31, 2003: Message edited by: Marlene Miller ]
Good, I am glad you understand final parameters referenced by inner classes. Is that the only case? The Java Programming Language (where I get many insights into the language) says �Local variables and parameters are usually declared final only when they will be accessed by a local, or anonymous, inner class�though some people advocate always making parameters final, as a matter of style.�
Post by:autobot
It's weird that we cook bacon and bake cookies. Eat this tiny ad:
a bit of art, as a gift, that will fit in a stocking