Michał Szewczyk Michał Szewczyk - 1 month ago 9
Java Question

Final variables in class file format

Does class file format provide support for final keyword in case of using it with variables?

Or it just deduce the effective finality of variable from code and JIT compiler perform optimalisation based on it?


Here, in class file format documentaion they mentioned about final keyword, but only in case of using it with final block and final class.
There is nothing about final variables.

I will be grateful for an answer.

Answer

No, there is no such information encoded in class file.

You may easily verify this by compiling a source file with a final local variable and without final - the result classes will be identical.

However, Java 8 added MethodParameters attribute that records information about names and access flags of method arguments. This means, you can check whether a method argument is final or not.

Just-in-time compilers do not need to know about final locals - they can easily determine the actual scope of any expression. Even if a variable is not final, e.g.

    int x = 1;
    // ... code A ...

    x = 2;
    // ... code B ...

the compilers will optimize the code A as if x is always 1, and the code B as if x is always 2.

Comments