Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javac treating static final differently based on assignment method

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?

like image 463
MilesHampson Avatar asked Jul 26 '13 15:07

MilesHampson


3 Answers

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.

like image 107
Cyrille Ka Avatar answered Oct 23 '22 19:10

Cyrille Ka


It is purely a case of compiler optimization where it ignores a direct assignment and does consider indirect assignment of literals.

like image 34
Syed Siraj Uddin Avatar answered Oct 23 '22 19:10

Syed Siraj Uddin


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.

like image 2
Narendra Pathai Avatar answered Oct 23 '22 19:10

Narendra Pathai