When I compile:
public static final boolean FOO = false;
public static final void fooTest() {
if (FOO) {
System.out.println("gg");
}
}
I get an empty method fooTest() {}
. However when I compile:
static boolean isBar = false;
public static final boolean BAR = isBar;
public static final void fooTest() {
if (BAR) {
System.out.println("gg");
}
}
the if statement is included in the compiled class file. Does this mean there are two different "types" of static final in java, or is this just a compiler optimization?
In the first case, the compiler does an optimization. It knows Foo
will always be false
and kill the code than will never be reached.
In the second case, you are assigning the value of the non-final variable isBar
to BAR
. The compiler can't tell if the variable isBar
has been modified somewhere else, especially if it is not private. Therefore it is not sure of the value of BAR
. Therefore he can not do the optimization.