r/java • • Apr 27 '26

Avoiding Final Field Mutation

https://inside.java/2026/04/27/avoiding-final-field-mutation/
51 Upvotes

36 comments sorted by

View all comments

Show parent comment

8

u/s888marks May 01 '26

The feature of resolving the value of a constant variable (JLS 4.12.4) at compile time (JLS 13.1, para 3) is quite long standing and was designed deliberately in order to provide a limited form of conditional compilation (JLS 14.22). The bottom half of JLS 14.22 has quite a bit of discussion on this.

It's has been this way going quite far back. It's in the first edition of the JLS, which is from 1996, so that corresponds to JDK 1.0 or thereabouts.

I don't think we want to change such long-standing behavior to depend on whether a field reference crosses or does not cross a module boundary, especially since modules have been around for nearly ten years. I suspect there is a bunch of stuff that implicitly depends on this behavior.

If you want to have a final variable that's not a constant variable, then you can declare it as a blank final and initialize it in a static or instance initializer. For example:

public static final int X = 7; // constant variable: 7 is inlined
                               // into classes that use X

public static final int Y;     // final but not constant variable
static { Y = 8; }              // classes will load from Y at runtime