Compile-time constants and variables

Compile time constant must be:

  • declared final
  • primitive or String
  • initialized within declaration
  • initialized with constant expression

So private final int x = getX(); is not constant.

To the second question private int y = 10; is not constant (non-final in this case), so optimizer cannot be sure that the value would not change in the future. So it cannot optimize it as good as constant value. The answer is: No, it is not treated the same way as compile time constant.


The JLS makes the following distinctions between final variables and constants:

final variables

A variable can be declared final. A final variable may only be assigned to once. It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment (§16 (Definite Assignment)).

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object. This applies also to arrays, because arrays are objects; if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

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

constants

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

From this definition, we can discern that a constant must be:

  • declared final
  • of primitive type or type String
  • initialized within its declaration (not a blank final)
  • initialized with a constant expression

What about compile-time constants?

The JLS does not contain the phrase compile-time constant. However, programmers often use the terms compile-time constant and constant interchangeably.

If a final variable does not meet the criteria outlined above to be considered a constant, it should technically be referred to as a final variable.