Mar 8, 2017

Compile time constants and Run time constants

Compile time constants:

These are the primitives(int, char, byte and short) and strings that are declared with keyword final and initialized at the time of declaration (value should be known to the compiler at the compile time).

For example:

public final int x = 10;            -> 1

Here the variable x is declared with keyword final and initialized at the declaration time. It is called as COMPILE TIME CONSTANT (Since, the identifiers that are declared as final and initialized once, their value cannot be changed later).

If we look at another case,

public static final int x = 10;     -> 2
            
This is also a COMPILE TIME CONSTANT.

The basic difference between 1 and 2 is static. It means that variable is related to the class but not object.
      1 -> It allocates the memory for every object with the given value.
      2 -> It allocates the memory once for the whole class and that can be accessed with either the class name or with the objects.
  • These Compile time constants are used in switch case statement.
For example:

public final int x = 10;
public final int y;
y=6;
switch(a+b){
case x:                 // no error
case y:                // compile error
}

Let us discuss, how the case condition works based on the values?

The JIT compiler transforms the switch statements into JVM bytecode tableswitch or lookupswitch for which the values must be COMPILE TIME CONSTANTS and also they must be unique.

In the above case, x is a compile time constant, since it's value can be determined at the compile time, whereas y is a constant variable but not compile time constant, since it may or may not be initialized in the code. i.e. there can be any other statements in between the initialization.

if (a == 1) {
    y = 6;
} else {
    y = 4;
}

From the compiler point of view, it is like using a variable that might not be initialized. Hence it is called as RUN TIME CONSTANT (Since it is initialized at RUN TIME only).

For example:

public static final int x = getValue();

Here, the compiler won't treat it as COMPILE TIME CONSTANT since the value returned by the method may or may not be assigned to the variable x. It is treated as RUN TIME CONSTANT.