Why is the final variable always a constant expression?

In the code below:

final int a; a=2; byte b=a; // error: possible loss of precision 

Why am I getting this error? Is a final compile time variable a constant constant and, therefore, implicitly tapers to a byte at the time of assignment?

In other words, the code not shown above is equivalent:

 final int a=2; byte b=a; 
+42
java expression constants compile-time-constant
Jun 11 '15 at 15:33
source share
3 answers

The compiler is not so smart.

We can say that the value will always be 2. But what if we had something like this?

 class ABC{ final int a; public ABC(){ if(Math.random() < .5){ a = 2; } else{ a = 12345; } byte b = a; } } 

The compiler is not smart enough to talk about all these cases, so it gives you an error.

+40
Jun 11 '15 at 15:43
source share

From JLS

Empty final is the final variable, in the declaration of which there is no initializer.

A constant variable is a final variable of a primitive type or String type that is initialized with a constant expression (ยง15.28).

Your variable

 final int a; 

is an empty final variable. He lacks an initializer. The second paragraph does not apply to it, since it is not initialized upon declaration. Therefore, this is not a constant expression.

This also applies to fields.

+49
Jun 11 '15 at 15:37
source share

Since the final variables can be delayed initialized and the compiler cannot determine for b that it matters in the case branch.

+2
Jun 11 '15 at 15:37
source share



All Articles