Java static final values replaced in code when compiling?

Yes, the Java compiler does replace static constant values like SIZE in your example with their literal values.

So, if you would later change SIZE in class A but you don’t recompile class b, you will still see the old value in class b. You can easily test this out:

file A.java

public class A {
    public static final int VALUE = 200;
}

file B.java

public class B {
    public static void main(String[] args) {
        System.out.println(A.VALUE);
    }
}

Compile A.java and B.java. Now run: java B

Change the value in A.java. Recompile A.java, but not B.java. Run again, and you’ll see the old value being printed.

Leave a Comment