In java, say I have the following
==fileA.java==
class A
{
public static final int SIZE = 100;
}
Then in another file I use this valu
As an optimization the compiler will inline that final variable.
So at compile time it will look like.
class b
{
Object[] temp = new Object[100];
}
Java does optimise these sorts of values but only if they are in the same class. In this case the JVM looks in A.SIZE rather than optimizing it because of the usage case you are considering.
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.
Actually I ran into this bizarreness a while ago.
This will compile "100" into class b directly. If you just recompile class A, this will not update the value in class B.
On top of that, the compiler may not notice to recompile class b (at the time I was compiling single directories and class B was in a separate directory and compiling a's directory did not trigger a compile of B)
The important concept here is that the static final
field is initialised with a compile-time constant, as defined in the JLS. Use a non-constant initialiser (or non-static
or non-final
) and it wont be copied:
public static final int SIZE = null!=null?0: 100;
(null
is not a *compile-time constant`.)
If static final field is null at the time of compiling then it doesn't get replaced with null (which is actually its value)
A.java
class A{
public static final String constantString = null;
}
B.java
class B{
public static void main(String... aa){
System.out.println(A.constantString);
}
}
Compile both A.java and B.java and run java B
Output will be null
Now Update A.java with following code and compile only this class.
class A{
public static final String constantString = "Omg! picking updated value without re-compilation";
}
Now run java B
Output will be Omg! picking updated value without re-compilation