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.
It is purely a case of compiler optimization where it ignores a direct assignment and does consider indirect assignment of literals.
In the first case static final
fields are constants which are known at compile
time. So the compiler optimizes and inlines the constant
.
In the second case the field is non-final
variable
and cannot be inlined by the compiler as it can change.
class Test{
public static final boolean BOOL = true; //CONSTANT KNOWN AT COMPILE TIME
public void someMethod(){
while(BOOL){
//some code
}
}
//OPTIMIZED VERSION DONE BY COMPILER
public void someMethod(){
while(true){ //There is no need for accessing BOOL if it is not going to change and compiler understands that so inlines the value of constant
}
}
}
You can look at the compiled code using some de-compiler tools and you will find the optimized method that I have written in the class file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With