What javac does
Compile-time constants
Copied into the code that uses them, so they are never read at run time.
A static final field initialised with a compile-time constant is not read at run time at all. javac copies its value into the code that uses it, and records it in a ConstantValue attribute on the field.
The source
// Compile-time constants: copied into the code that uses them, so getstatic never happens.
public class Constants {
static final int LIMIT = 1000;
static final String NAME = "limit";
static final long BIG = 1L << 40;
static final int COMPUTED = Integer.parseInt("7");
static int check(int n) {
if (n > LIMIT) {
System.out.println(NAME + " exceeded");
return COMPUTED;
}
return (int) (BIG >> 38);
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
n > LIMITcompiles tosipush1000: there is nogetstatic.NAME + " exceeded"is folded into one String constant,"limit exceeded".(int) (BIG >> 38)is folded too: the method returnsiconst_4.COMPUTEDis set by a method call, so it is not a constant: it gets a realgetstatic, and aputstaticin the static initialiser.- The catch: another class that uses
LIMITkeeps the copied value until it is recompiled, even after you change it here.
Constants.class
static int check(int n)
static { … }
javac --release 8 to 25 (the same bytecode for every release)
6
static final int COMPUTED = Integer.parseInt("7");