Comment space too small, so here is some more information for you on the use of static final
. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:
You can see this in action by creating three classes (in separate files):
public class DisplayValue {
private String value;
public DisplayValue(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
public class Constants {
public static final int INT_VALUE = 0;
public static final DisplayValue VALUE = new DisplayValue("A");
}
public class Test {
public static void main(String[] args) {
System.out.println("Int = " + Constants.INT_VALUE);
System.out.println("Value = " + Constants.VALUE);
}
}
Compile these and run Test, which prints:
Int = 0
Value = A
Now, change Constants
to have a different value for each and just compile class Constants
. When you execute Test
again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:
public class Constants {
public static final int INT_VALUE = 2;
public static final DisplayValue VALUE = new DisplayValue("X");
}
Run Test without recompiling Test.java
:
Int = 0
Value = X
Note that any other type used with static final
is kept as a reference.
Similar to C/C++ #if/#endif, a constant literal or one defined through static final
with primitives, used in a regular Java if
condition and evaluates to false
will cause the compiler to strip the byte code for the statements within the if
block (they will not be generated).
private static final boolean DEBUG = false;
if (DEBUG) {
...code here...
}
The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG
to true
then it would be.