Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't a final variable always a constant expression?

In the below code:

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

Why do I get this error? Isn't a final variable compile time constant expression and hence implicitly narrowed to byte during the assignment?

In other words isn't the above code equivalent to:

final int a=2; byte b=a; 
like image 548
paidedly Avatar asked Jun 11 '15 15:06

paidedly


People also ask

Is final variable a constant?

Constant is the concept, the property of the variable. final is the java keyword to declare a constant variable.

Is final the same as constant?

The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object's entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.

Why would you use a constant instead of a variable?

Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.

What is a final constant?

The main difference between final variable and a constant (static and final) is that if you create a final variable without static keyword, though its value is un-modifiable, a separate copy of the variable is created each time you create a new object.


2 Answers

From the JLS

A blank final is a final variable whose declaration lacks an initializer.

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

Your variable

final int a; 

is a blank final variable. It lacks an initializer. The second paragraph doesn't apply to it because it is not initialized at declaration. It therefore isn't a constant expression.

This applies to fields as well.

like image 101
Sotirios Delimanolis Avatar answered Oct 05 '22 13:10

Sotirios Delimanolis


The compiler isn't that smart.

We can tell 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 tell these two cases apart, so it gives you an error instead.

like image 22
Kevin Workman Avatar answered Oct 05 '22 14:10

Kevin Workman