Compile-time constants and variables

NINCOMPOOP picture NINCOMPOOP · Jan 31, 2012 · Viewed 37.2k times · Source

The Java language documentation says:

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant.

My understanding is if we have a piece of code:

private final int x = 10;

Then, the compiler will replace every occurrence of x in the code with literal 10.


But suppose the constant is initialized at run-time:

private final int x = getX(); // here getX() returns an integer value at run-time.

Will there be any performance drop (howsoever negligible it may be) compared to the compile-time constant?


Another question is whether the below line of code:

private int y = 10; // here y is not final

is treated in same way as compile-time constant by the compiler?


Finally, what I understand from the answers are:

  1. final static means compile-time constant
  2. just final means it's a constant but is initialized at run-time
  3. just static means initialized at run-time
  4. without final is a variable and wouldn't be treated as constant.

Is my understanding correct?

Answer

msi picture msi · Jan 31, 2012

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.